Java Notes
20+ essential Java string programs with complete solutions, detailed explanations, and output covering palindrome, anagram, reversal, frequency count, and all common string coding problems.
This section contains 20 essential string programs that cover the most commonly asked problems in coding interviews and exams. Each includes complete code, logic explanation, and output.
Program 1: Reverse a String
Original: Hello World Reversed (StringBuilder): dlroW olleH Reversed (char array): dlroW olleH
Program 2: Check Palindrome
public class PalindromeCheck {
public static void main(String[] args) {
String[] words = {"madam", "hello", "racecar", "java", "abcba"};
for (String word : words) {
String reversed = new StringBuilder(word).reverse().toString();
boolean isPalindrome = word.equals(reversed);
System.out.println(word + " → " + (isPalindrome ? "Palindrome ✓" : "Not palindrome ✗"));
}
}
}madam → Palindrome ✓ hello → Not palindrome ✗ racecar → Palindrome ✓ java → Not palindrome ✗ abcba → Palindrome ✓
Program 3: Count Vowels and Consonants
String: "Java Programming Language" Vowels: 8 Consonants: 14 Spaces: 2 Digits: 0
Program 4: Check Anagram
Two strings are anagrams if they contain the same characters in different order.
listen & silent → Anagram: true hello & world → Anagram: false Triangle & Integral → Anagram: true
Program 5: Character Frequency Count
import java.util.LinkedHashMap;
import java.util.Map;
public class CharFrequency {
public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println("String: \"" + str + "\"");
System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println(" '" + entry.getKey() + "' → " + entry.getValue());
}
}
}String: "programming" Character frequencies: 'p' → 1 'r' → 2 'o' → 1 'g' → 2 'a' → 1 'm' → 2 'i' → 1 'n' → 1
Program 6: First Non-Repeating Character
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeating {
public static void main(String[] args) {
String str = "aabbcddeffg";
LinkedHashMap<Character, Integer> freq = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println("String: \"" + str + "\"");
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
if (entry.getValue() == 1) {
System.out.println("First non-repeating: '" + entry.getKey() + "'");
return;
}
}
System.out.println("No non-repeating character found");
}
}String: "aabbcddeffg" First non-repeating: 'c'
Program 7: Remove Duplicate Characters
Original: programming Without duplicates: progamin
Program 8: Count Words in a String
public class WordCount {
public static void main(String[] args) {
String str = " Java is a powerful programming language ";
// Method 1: Split and filter empty strings
String[] words = str.trim().split("\\s+");
System.out.println("String: \"" + str.trim() + "\"");
System.out.println("Word count: " + words.length);
System.out.println("Words: " + java.util.Arrays.toString(words));
}
}String: "Java is a powerful programming language" Word count: 6 Words: [Java, is, a, powerful, programming, language]
Program 9: Reverse Words in a String
Original: Hello World Java Programming Words reversed: Programming Java World Hello
Program 10: Capitalize First Letter of Each Word
public class CapitalizeWords {
public static void main(String[] args) {
String str = "hello world java programming";
StringBuilder result = new StringBuilder();
String[] words = str.split(" ");
for (String word : words) {
if (!word.isEmpty()) {
result.append(Character.toUpperCase(word.charAt(0)));
result.append(word.substring(1));
result.append(" ");
}
}
System.out.println("Original: " + str);
System.out.println("Capitalized: " + result.toString().trim());
}
}Original: hello world java programming Capitalized: Hello World Java Programming
Program 11: Check if String Contains Only Digits
public class OnlyDigits {
public static void main(String[] args) {
String[] inputs = {"12345", "123abc", "00000", "", "3.14"};
for (String input : inputs) {
boolean allDigits = !input.isEmpty() && input.chars().allMatch(Character::isDigit);
System.out.println("\"" + input + "\" → only digits: " + allDigits);
}
}
}"12345" → only digits: true "123abc" → only digits: false "00000" → only digits: true "" → only digits: false "3.14" → only digits: false
Program 12: Find Longest Word
public class LongestWord {
public static void main(String[] args) {
String str = "Java is a powerful programming language";
String[] words = str.split(" ");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
System.out.println("String: \"" + str + "\"");
System.out.println("Longest word: \"" + longest + "\" (length: " + longest.length() + ")");
}
}String: "Java is a powerful programming language" Longest word: "programming" (length: 11)
Program 13: String Compression (Run-Length Encoding)
Original: aaabbbccddddeeee (length: 16) Compressed: a3b3c2d4e4 (length: 10)
Program 14: Check if Two Strings are Rotations
abcde & cdeab → Rotation: true abcde & abced → Rotation: false waterbottle & erbottlewat → Rotation: true
Program 15: Convert String to Title Case
public class TitleCase {
public static void main(String[] args) {
String str = "the quick brown fox jumps over the lazy dog";
StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;
for (char c : str.toCharArray()) {
if (c == ' ') {
capitalizeNext = true;
result.append(c);
} else if (capitalizeNext) {
result.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
result.append(c);
}
}
System.out.println("Original: " + str);
System.out.println("Title Case: " + result);
}
}Original: the quick brown fox jumps over the lazy dog Title Case: The Quick Brown Fox Jumps Over The Lazy Dog
Program 16: Find All Substrings
All substrings of "abc": a ab abc b bc c Total substrings: 6
Program 17: Remove All White Spaces
public class RemoveSpaces {
public static void main(String[] args) {
String str = " Hello World Java ";
// Method 1: replaceAll
String noSpaces = str.replaceAll("\\s+", "");
// Method 2: StringBuilder
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != ' ') sb.append(c);
}
System.out.println("Original: \"" + str + "\"");
System.out.println("No spaces: \"" + noSpaces + "\"");
System.out.println("StringBuilder: \"" + sb + "\"");
}
}Original: " Hello World Java " No spaces: "HelloWorldJava" StringBuilder: "HelloWorldJava"
Program 18: Count Occurrences of a Substring
String: "Java is great. Java is powerful. Java is everywhere." Substring: "Java" Occurrences: 3
Program 19: Check Pangram
A pangram contains every letter of the alphabet at least once.
"The quick brown fox jumps over the lazy dog" Pangram: true "Hello World Java Programming" Pangram: false
Program 20: Longest Palindrome Substring
String: "babad" Longest palindrome substring: "bab"
Common Mistakes
- Forgetting Strings are immutable — must assign results of operations
- Not handling null/empty strings — always check before processing
- Using == instead of .equals() for content comparison
- Off-by-one in substring() — endIndex is exclusive
- Not escaping regex special characters in split() and replaceAll()
Best Practices
- Use StringBuilder for building strings in loops
- Use library methods when available (trim, split, replace)
- Handle edge cases — empty string, null, single character
- Consider case sensitivity — use toLowerCase() when comparing
- Use char arrays for in-place modifications
- Know regex basics for pattern matching problems
- Use HashMap for frequency counting problems
- Test with varied inputs — spaces, special chars, Unicode
Interview Questions
Q1: How to reverse a string without using built-in reverse? Use two-pointer swap on char array, or build from end using charAt.
Q2: Time complexity of checking anagram with sorting? O(n log n) for sorting. O(n) is possible with frequency array.
Q3: How to find first non-repeating character in O(n)? Use LinkedHashMap to maintain insertion order with frequency counts. First entry with count 1 is the answer.
Q4: How to check if strings are rotations of each other? If same length and (s1 + s1).contains(s2), they are rotations. O(n) time.
Q5: What is run-length encoding? Compressing consecutive same characters into character+count: "aaabbb" → "a3b3".
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for String Programs — Fundamentals.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, strings, string
Related Java Master Course Topics