Java String Interview Questions: 15 Essential Programs (PDF)

Java String interview questions

15 Most-Asked Java String Interview Questions for Experienced Developers

Practice the string coding problems that regularly appear in Java interviews, with simple explanations, working programs, and time-complexity notes.

String programs look simple, but they reveal a lot about a developer. An interviewer can use one short problem to check your knowledge of loops, arrays, collections, object mutability, and algorithmic complexity. That is why Java String interview questions remain common in coding rounds for both freshers and experienced developers.

This guide covers 15 most-asked programs for experienced developers, with clear answers, complexity analysis, practical examples, and a free PDF download for offline revision.
.

1. How do you reverse a string using StringBuilder?

The shortest practical answer is to create a mutable StringBuilder and call its reverse() method. This is usually the best answer when the interviewer allows built-in methods.

public class ReverseStringWithBuilder {
    public static void main(String[] args) {
        String str = "dinesh";

        StringBuilder builder = new StringBuilder(str);
        builder.reverse();

        System.out.println(builder); // hsenid
    }
}

How it works: the String remains unchanged because strings are immutable. The StringBuilder object is mutable, so reverse() changes that builder and returns it. println() calls its toString() representation automatically.

Complexity: O(n) time and O(n) additional space for the builder.

2. How do you reverse a string without using reverse()?

Convert the string to a character array, then swap the first and last characters while moving toward the centre. This version demonstrates the two-pointer technique.

public class ReverseString {
    public static void main(String[] args) {
        String name = "Dinesh";
        char[] characters = name.toCharArray();

        int start = 0;
        int end = characters.length - 1;

        while (start < end) {
            char temp = characters[start];
            characters[start] = characters[end];
            characters[end] = temp;
            start++;
            end--;
        }

        System.out.println(new String(characters)); // hseniD
    }
}

The actual output is hseniD. A loop that repeatedly performs reversed = reversed + ch also works, but it creates many temporary strings and can take O(n²) time.

Complexity: O(n) time and O(n) space because Java must create the character array.

3. How do you check whether a string is a palindrome?

A palindrome reads the same from left to right and right to left, such as madam, level, or radar. Compare matching characters from both ends and stop as soon as they differ.

public class PalindromeCheck {
    public static void main(String[] args) {
        String str = "madam";
        boolean isPalindrome = true;

        for (int i = 0; i < str.length() / 2; i++) {
            if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
                isPalindrome = false;
                break;
            }
        }

        System.out.println(isPalindrome); // true
    }
}

Only half of the string needs to be checked. Ask whether the comparison should ignore spaces, punctuation, or letter case before coding a production version.

Complexity: O(n) time and O(1) extra space.

4. How do you find the first non-repeating character?

Use a map to count every character, then scan the original string a second time. The second pass is important because a regular HashMap does not preserve the string’s order.

import java.util.HashMap;
import java.util.Map;

public class FirstNonRepeatingCharacter {
    public static void main(String[] args) {
        String str = "ddonneejnkk";
        Map<Character, Integer> frequency = new HashMap<>();

        for (char ch : str.toCharArray()) {
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        for (char ch : str.toCharArray()) {
            if (frequency.get(ch) == 1) {
                System.out.println(ch); // j
                return;
            }
        }

        System.out.println("No unique character");
    }
}

For lowercase English letters only, an int[26] frequency array is a faster, fixed-size alternative.

Complexity: O(n) time and O(k) space, where k is the number of distinct characters.

5. How do you check whether two strings are anagrams?

Two strings are anagrams if they contain the same characters with the same frequencies. For lowercase English letters, one array of 26 counters is enough.

public class AnagramCheck {
    public static boolean isAnagram(String first, String second) {
        if (first.length() != second.length()) {
            return false;
        }

        int[] frequency = new int[26];

        for (char ch : first.toCharArray()) {
            frequency[ch - 'a']++;
        }

        for (char ch : second.toCharArray()) {
            frequency[ch - 'a']--;
        }

        for (int count : frequency) {
            if (count != 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("listen", "silent")); // true
    }
}

This code assumes lowercase az. For Unicode text or mixed characters, use a HashMap<Character, Integer>. Clarify whether spaces and case should be ignored.

Complexity: O(n) time and O(1) space because the array size is fixed.

6. How do you count the frequency of each character?

A frequency map connects each character with the number of times it occurs. getOrDefault() keeps the update concise.

import java.util.LinkedHashMap;
import java.util.Map;

public class CharacterFrequency {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (char ch : str.toCharArray()) {
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

LinkedHashMap is used here so the output follows the order in which characters first appear.

Complexity: O(n) time and O(k) space.

7. How do you find duplicate characters in a string?

Count the characters, then print only entries whose value is greater than one.

import java.util.LinkedHashMap;
import java.util.Map;

public class FindDuplicateCharacters {
    public static void main(String[] args) {
        String str = "dineshh";
        Map<Character, Integer> frequency = new LinkedHashMap<>();

        for (char ch : str.toCharArray()) {
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        for (Map.Entry<Character, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " -> " + entry.getValue());
            }
        }
    }
}

The output is h -> 2. Checking for == 1 would find unique characters, not duplicates.

Complexity: O(n) time and O(k) space.

8. How do you remove duplicate characters while preserving order?

A LinkedHashSet removes duplicates and preserves insertion order. Append its contents to a new result.

import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateCharacters {
    public static void main(String[] args) {
        String str = "dinnesh";
        Set<Character> unique = new LinkedHashSet<>();

        for (char ch : str.toCharArray()) {
            unique.add(ch);
        }

        StringBuilder result = new StringBuilder();
        for (char ch : unique) {
            result.append(ch);
        }

        System.out.println(result); // dinesh
    }
}

Complexity: O(n) average time and O(k) space.

9. How do you find duplicate words and their counts?

Normalise the sentence, split it on one or more whitespace characters, count each word, and print counts greater than one.

import java.util.LinkedHashMap;
import java.util.Map;

public class DuplicateWords {
    public static void main(String[] args) {
        String text = "Java is great and Java is powerful and Java is fast";
        String[] words = text.toLowerCase().trim().split("\\s+");
        Map<String, Integer> frequency = new LinkedHashMap<>();

        for (String word : words) {
            frequency.put(word, frequency.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " -> " + entry.getValue());
            }
        }
    }
}

The output includes java -> 3, is -> 3, and and -> 2. For real text, remove punctuation before splitting if java and java, should count as the same word.

10. How do you reverse each word in a sentence?

Split the sentence into words, reverse the characters of each word, and preserve the original word order.

public class ReverseEachWord {
    public static void main(String[] args) {
        String text = "Java Concept Of The Day";
        String[] words = text.split("\\s+");
        StringBuilder result = new StringBuilder();

        for (String word : words) {
            for (int i = word.length() - 1; i >= 0; i--) {
                result.append(word.charAt(i));
            }
            result.append(' ');
        }

        System.out.println(result.toString().trim());
        // avaJ tpecnoC fO ehT yaD
    }
}

This is different from reversing the entire sentence because the positions of the words do not change.

Complexity: O(n) time and O(n) space.

11. How do you find the longest substring without repeating characters?

Use a sliding window. Expand the right edge while characters are unique; when a duplicate appears, remove characters from the left until the window is valid again.

import java.util.HashSet;
import java.util.Set;

public class LongestUniqueSubstring {
    public static void main(String[] args) {
        String str = "abcabca";
        Set<Character> window = new HashSet<>();

        int start = 0;
        int end = 0;
        int maxLength = 0;

        while (end < str.length()) {
            char current = str.charAt(end);

            if (!window.contains(current)) {
                window.add(current);
                end++;
                maxLength = Math.max(maxLength, window.size());
            } else {
                window.remove(str.charAt(start));
                start++;
            }
        }

        System.out.println(maxLength); // 3
    }
}

A HashSet keeps membership checks near O(1) on average. Using an ArrayList gives the same result but makes contains() slower.

Complexity: O(n) average time and O(k) space.

12. How do you count uppercase characters?

For basic English letters, compare each character with the range 'A' to 'Z'.

public class UppercaseCharacterCount {
    public static void main(String[] args) {
        String str = "DjninDmmdD";
        int count = 0;

        for (char ch : str.toCharArray()) {
            if (ch >= 'A' && ch <= 'Z') {
                count++;
            }
        }

        System.out.println(count); // 3
    }
}

Use Character.isUpperCase(ch) when the requirement includes Unicode uppercase letters.

Complexity: O(n) time and O(1) space.

13. How do you count vowels and consonants?

Convert the input to lowercase, ignore non-letter characters, and test each remaining character against the five vowels.

public class VowelAndConsonantCount {
    public static void main(String[] args) {
        String str = "hello world".toLowerCase();
        int vowels = 0;
        int consonants = 0;

        for (char ch : str.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                if (ch == 'a' || ch == 'e' || ch == 'i'
                        || ch == 'o' || ch == 'u') {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }

        System.out.println("Vowels: " + vowels);       // 3
        System.out.println("Consonants: " + consonants); // 7
    }
}

The inclusive checks >= and <= matter. Using only > and < would wrongly exclude a and z.

14. How do you separate lowercase and uppercase characters?

Maintain two builders and append each letter to the correct one. Explicit checks prevent digits and symbols from being treated as uppercase.

public class SeparateCharactersByCase {
    public static void main(String[] args) {
        String str = "aBsNbcD";
        StringBuilder lowercase = new StringBuilder();
        StringBuilder uppercase = new StringBuilder();

        for (char ch : str.toCharArray()) {
            if (Character.isLowerCase(ch)) {
                lowercase.append(ch);
            } else if (Character.isUpperCase(ch)) {
                uppercase.append(ch);
            }
        }

        System.out.println("Lowercase: " + lowercase); // asbc
        System.out.println("Uppercase: " + uppercase); // BND
    }
}

Complexity: O(n) time and O(n) space for the results.

15. How do you perform basic string compression?

Count consecutive occurrences of the current character. When the next character changes—or the loop reaches the end—append the character and its count.

public class StringCompression {
    public static void main(String[] args) {
        String str = "aabbccc";
        StringBuilder result = new StringBuilder();
        int count = 1;

        for (int i = 0; i < str.length(); i++) {
            if (i < str.length() - 1
                    && str.charAt(i) == str.charAt(i + 1)) {
                count++;
            } else {
                result.append(str.charAt(i)).append(count);
                count = 1;
            }
        }

        System.out.println(result); // a2b2c3
    }
}

This is run-length encoding: it counts consecutive characters, not total frequency. For example, abab becomes a1b1a1b1, not a2b2.

Complexity: O(n) time and O(n) space.

How to answer string coding questions in an interview

Before writing code, repeat the requirement in your own words. Ask whether the input can be null or empty, whether case matters, and whether it contains spaces, punctuation, or Unicode characters. Explain the simple approach first, then improve it if necessary. Finally, test one normal input and one edge case, and state the time and space complexity. This short routine makes even a basic solution sound clear and professional.

Frequently asked questions

Which Java string programs are most important for interviews?

Start with string reversal, palindrome checking, anagrams, character frequency, the first non-repeating character, duplicate removal, and the longest substring without repeating characters. Together, they cover loops, two pointers, maps, sets, and sliding windows.

Should I use built-in methods during a coding interview?

Ask the interviewer. If built-in methods are allowed, a clean library-based solution is valid. However, be prepared to explain or code the underlying logic because interviewers often add a “without using built-in methods” condition.

Why is StringBuilder preferred inside loops?

Java strings are immutable, so repeated concatenation may create many temporary objects. StringBuilder is mutable and is usually more efficient when a result is assembled through repeated appends.

What is the difference between StringBuilder and StringBuffer?

StringBuilder is not synchronised and is normally faster for local, single-threaded work. StringBuffer uses synchronised methods and may be chosen when the same mutable buffer is shared across threads.

How can I improve at Java String interview questions?

Write each program without copying it, explain the data structure you selected, calculate complexity, and test empty, single-character, repeated-character, and mixed-case inputs. Understanding a small group of patterns is more useful than memorising dozens of answers.

Conclusion

These 15 Java String interview questions build the core skills needed for many entry-level and intermediate coding rounds. Begin with the direct solution, make your assumptions clear, and improve performance with the right structure—such as a frequency map, set, two-pointer scan, or sliding window.

The goal is not to memorise every line. Practise until you can explain why the solution works, identify its limits, and adapt it when the interviewer changes the requirements.

Scroll to Top