Master fundamental Java concepts with these beginner-friendly programs
Check if two strings are anagrams of each other.
Write a program to check if two strings are anagrams of each other.
"listen", "silent"
Yes, they are anagrams.
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("Yes, they are anagrams.");
} else {
System.out.println("No, they are not anagrams.");
}
}
public static boolean areAnagrams(String s1, String s2) {
// Remove spaces and convert to lowercase
s1 = s1.replaceAll("\\s", "").toLowerCase();
s2 = s2.replaceAll("\\s", "").toLowerCase();
if (s1.length() != s2.length()) {
return false;
}
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}
Remove all duplicate characters from a string.
Write a program to remove all duplicate characters from a string.
"programming"
"progamin"
import java.util.LinkedHashSet;
public class RemoveDuplicateChars {
public static void main(String[] args) {
String input = "programming";
String result = removeDuplicates(input);
System.out.println(result);
}
public static String removeDuplicates(String str) {
LinkedHashSet set = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
set.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : set) {
sb.append(c);
}
return sb.toString();
}
}
Find the longest word in a sentence.
Write a program to find the longest word in a sentence.
"The quick brown fox jumped over the lazy dog"
Longest Word: "jumped"
public class LongestWordInSentence {
public static void main(String[] args) {
String sentence = "The quick brown fox jumped over the lazy dog";
String longestWord = findLongestWord(sentence);
System.out.println("Longest Word: \"" + longestWord + "\"");
}
public static String findLongestWord(String sentence) {
String[] words = sentence.split("\\s+");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
return longest;
}
}
Count the frequency of each character in a string.
Write a program to count the frequency of each character in a string.
"balloon"
b:1 a:1 l:2 o:2 n:1
import java.util.HashMap;
import java.util.Map;
public class CharacterFrequencyCount {
public static void main(String[] args) {
String input = "balloon";
Map freqMap = new HashMap<>();
for (char ch : input.toCharArray()) {
freqMap.put(ch, freqMap.getOrDefault(ch, 0) + 1);
}
for (Map.Entry entry : freqMap.entrySet()) {
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
}
}
}
Check if one string is a rotation of another.
Write a program to check if one string is a rotation of another.
"waterbottle", "erbottlewat"
Yes, it is a rotation
public class StringRotationCheck {
public static boolean isRotation(String s1, String s2) {
if (s1.length() != s2.length()) return false;
String temp = s1 + s1;
return temp.contains(s2);
}
public static void main(String[] args) {
String s1 = "waterbottle";
String s2 = "erbottlewat";
if (isRotation(s1, s2)) {
System.out.println("Yes, it is a rotation");
} else {
System.out.println("No, it is not a rotation");
}
}
}
Reverse the order of words in a sentence.
Write a program to reverse the order of words in a sentence.
"hello world program"
"program world hello"
public class ReverseWords {
public static String reverseWords(String sentence) {
String[] words = sentence.split(" ");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]);
if (i != 0) reversed.append(" ");
}
return reversed.toString();
}
public static void main(String[] args) {
String input = "hello world program";
System.out.println(reverseWords(input));
}
}
Compress the string by counting consecutive characters.
Compress the string by counting consecutive characters.
"aabcccccaaa"
"a2b1c5a3"
public class StringCompression {
public static String compress(String str) {
StringBuilder compressed = new StringBuilder();
int count = 1;
for (int i = 1; i <= str.length(); i++) {
if (i < str.length() && str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
compressed.append(str.charAt(i - 1));
compressed.append(count);
count = 1;
}
}
return compressed.toString();
}
public static void main(String[] args) {
String input = "aabcccccaaa";
System.out.println(compress(input));
}
}
Write a function to implement strstr() (find substring).
Write a function to implement strstr() (find substring).
"hello", "ll"
Found at index 2
public class StrStrImplementation {
public static int strstr(String haystack, String needle) {
int hLen = haystack.length();
int nLen = needle.length();
if (nLen == 0) return 0; // Empty needle
for (int i = 0; i <= hLen - nLen; i++) {
int j = 0;
while (j < nLen && haystack.charAt(i + j) == needle.charAt(j)) {
j++;
}
if (j == nLen) {
return i; // Found at index i
}
}
return -1; // Not found
}
public static void main(String[] args) {
String haystack = "hello";
String needle = "ll";
int index = strstr(haystack, needle);
if (index != -1) {
System.out.println("Found at index " + index);
} else {
System.out.println("Not found");
}
}
}
Write a program to convert a numeric string into an integer.
Write a program to convert a numeric string into an integer.
"12345"
Integer: 12345
public class StringToInteger {
public static int stringToInt(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException("Invalid numeric string");
}
result = result * 10 + (c - '0');
}
return result;
}
public static void main(String[] args) {
String numericString = "12345";
int number = stringToInt(numericString);
System.out.println("Integer: " + number);
}
}
Write a program to find the first non-repeating character in a string.
Write a program to find the first non-repeating character in a string.
"aabbcddee"
First Unique: c
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeatingChar {
public static char firstNonRepeatingChar(String str) {
Map charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (Map.Entry entry : charCount.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0'; // No unique char found
}
public static void main(String[] args) {
String input = "aabbcddee";
char result = firstNonRepeatingChar(input);
if (result != '\0') {
System.out.println("First Unique: " + result);
} else {
System.out.println("No unique character found.");
}
}
}
Check if a string has all unique characters.
Check if a string has all unique characters.
"abcdefg"
Yes, all characters are unique.
import java.util.HashSet;
import java.util.Set;
public class AllUniqueCharacters {
public static boolean areAllUnique(String str) {
Set chars = new HashSet<>();
for (char c : str.toCharArray()) {
if (chars.contains(c)) {
return false;
}
chars.add(c);
}
return true;
}
public static void main(String[] args) {
String input = "abcdefg";
if (areAllUnique(input)) {
System.out.println("Yes, all characters are unique.");
} else {
System.out.println("No, there are duplicate characters.");
}
}
}
Convert the first letter of each word to uppercase.
Convert the first letter of each word to uppercase.
"welcome to coding world"
"Welcome To Coding World"
public class TitleCaseConverter {
public static String toTitleCase(String str) {
String[] words = str.split("\\s+");
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() > 0) {
sb.append(Character.toUpperCase(word.charAt(0)));
sb.append(word.substring(1).toLowerCase());
sb.append(" ");
}
}
return sb.toString().trim();
}
public static void main(String[] args) {
String input = "welcome to coding world";
String result = toTitleCase(input);
System.out.println(result);
}
}
Generate all substrings of a string.
Write a program to generate all substrings of a string.
"abc"
"a", "ab", "abc", "b", "bc", "c"
public class AllSubstrings {
public static void main(String[] args) {
String str = "abc";
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
System.out.println(str.substring(i, j));
}
}
}
}
Count vowels and consonants in a string.
Write a program to count vowels and consonants in a string.
"hello world"
Vowels: 3, Consonants: 7
public class VowelConsonantCount {
public static void main(String[] args) {
String str = "hello world";
int vowels = 0, consonants = 0;
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
}
}
Check if a string contains only digits.
Write a program to check if a string contains only digits.
"123456"
Yes, it contains only digits.
public class DigitsOnlyCheck {
public static void main(String[] args) {
String str = "123456";
boolean isDigitsOnly = true;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
isDigitsOnly = false;
break;
}
}
if (isDigitsOnly) {
System.out.println("Yes, it contains only digits.");
} else {
System.out.println("No, it contains other characters.");
}
}
}
Character.isDigit().Find the length of the longest substring with all unique characters.
Find the length of the longest substring with all unique characters.
"abcabcbb"
Length: 3
import java.util.HashSet;
public class LongestUniqueSubstring {
public static void main(String[] args) {
String s = "abcabcbb";
System.out.println("Length: " + lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s) {
int maxLen = 0, start = 0;
HashSet<Character> set = new HashSet<>();
for (int end = 0; end < s.length(); end++) {
while (set.contains(s.charAt(end))) {
set.remove(s.charAt(start));
start++;
}
set.add(s.charAt(end));
maxLen = Math.max(maxLen, end - start + 1);
}
return maxLen;
}
}
Write a program to remove all non-alphabetic characters from a string.
Write a program to remove all non-alphabetic characters from a string.
"Hello@123#World!"
"HelloWorld"
public class RemoveNonAlphabetic {
public static void main(String[] args) {
String input = "Hello@123#World!";
String result = input.replaceAll("[^a-zA-Z]", "");
System.out.println(result);
}
}
[^a-zA-Z] to match all non-alphabetic characters.Check if a string is a pangram (contains all alphabets).
Check if a string is a pangram (contains all alphabets).
"The quick brown fox jumps over the lazy dog"
Yes, it's a pangram.
public class PangramCheck {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";
sentence = sentence.toLowerCase();
boolean[] alphabet = new boolean[26];
int index;
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch >= 'a' && ch <= 'z') {
index = ch - 'a';
if (!alphabet[index]) {
alphabet[index] = true;
count++;
}
}
}
if (count == 26) {
System.out.println("Yes, it's a pangram.");
} else {
System.out.println("No, it's not a pangram.");
}
}
}
Replace all spaces in a string with "%20".
Replace all spaces in a string with "%20".
"My name is Khan"
"My%20name%20is%20Khan"
public class ReplaceSpaces {
public static void main(String[] args) {
String input = "My name is Khan";
String output = input.replace(" ", "%20");
System.out.println(output);
}
}
replace() method to replace all spaces with "%20".Find the minimum characters to insert at the beginning to make a string palindrome.
Find the minimum characters to insert at the beginning to make a string palindrome.
"abcd"
Minimum Insertions: 3 (Result: "dcbabcd")
public class MinInsertionsPalindrome {
// Function to check if a string is palindrome
static boolean isPalindrome(String s) {
int start = 0, end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)) return false;
start++;
end--;
}
return true;
}
// Function to find minimum insertions at beginning
static int minInsertionsToMakePalindrome(String s) {
int count = 0;
String temp = s;
// Keep adding characters from end until palindrome formed
while (!isPalindrome(temp)) {
count++;
temp = s.charAt(s.length() - count) + temp;
}
return count;
}
public static void main(String[] args) {
String input = "abcd";
int minInsertions = minInsertionsToMakePalindrome(input);
// Construct the result string
StringBuilder sb = new StringBuilder(input);
for (int i = minInsertions - 1; i >= 0; i--) {
sb.insert(0, input.charAt(input.length() - 1 - i));
}
System.out.println("Minimum Insertions: " + minInsertions + " (Result: \"" + sb.toString() + "\")");
}
}