Autocoder

Java String Interview Questions

Last updated 2026-11-19

String is the class interviewers use to test whether you understand references, memory and immutability in one go. The standard sequence is: why is String immutable, what is the string pool, how many objects does new String("a") create, and what does a comparison with == print.

This page covers those and the practical APIs that trip people up in coding rounds, such as split, replaceAll and compareTo. For more mixed problems, see Java coding questions.

ImmutableYes, for thread safety, pooling and hash caching
Java version17 and later (text blocks, strip, repeat)
Common trap== versus equals on Strings

Pool and heap in one picture

String literals and compile-time constants are interned into a pool that lives on the heap. new String("x") always creates a fresh heap object. intern() returns the pooled instance, adding it if needed. Comparing with == compares those references, which is why the same-looking strings can print true or false.

Java String Interview Questions: questions with worked answers

  1. 1

    Why is String immutable in Java?

    easy

    Immutability makes strings safe to share between threads, safe as HashMap keys because the hash cannot change, and safe for the string pool because one literal can be reused. It also protects security-sensitive values such as class names and file paths from being altered after validation. The hash code is cached in the object after the first call.

  2. 2

    Predict the output for each == comparison.

    medium

    Literals with the same content share one pooled object. new String creates a distinct object. A compile-time constant expression is folded and interned, but concatenation involving a non-final variable is evaluated at runtime and creates a new object. intern() returns the pooled reference.

    java
    String a = "hello";
    String b = "hello";
    String c = new String("hello");
    String half = "hel";
    final String fhalf = "hel";
    System.out.println(a == b);                 // true
    System.out.println(a == c);                 // false
    System.out.println(a == c.intern());        // true
    System.out.println(a == "hel" + "lo");      // true  (constant)
    System.out.println(a == half + "lo");       // false (runtime concat)
    System.out.println(a == fhalf + "lo");      // true  (final constant)
  3. 3

    How many objects does new String("abc") create?

    medium

    Up to two. The literal "abc" becomes a pooled String object when the class is loaded (if an equal one is not already pooled), and new String copies it into a second object on the heap. The honest interview answer is: one on the heap at the call site, plus one in the pool if it was not there yet.

  4. 4

    String versus StringBuilder versus StringBuffer.

    easy

    String is immutable. StringBuilder is a mutable, unsynchronised character buffer and is the right choice for building strings in a single thread. StringBuffer has the same API with synchronised methods, so it is slower and rarely needed since a buffer shared across threads is usually a design smell. Concatenating in a loop with + creates a new String every pass, giving O(n squared) copying; StringBuilder.append is amortised O(1) per character.

    java
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 5; i++) sb.append(i).append(',');
    sb.setLength(sb.length() - 1);
    System.out.println(sb);            // 0,1,2,3,4
    System.out.println(sb.reverse());  // 4,3,2,1,0
  5. 5

    What does the + operator compile to, and is concatenation in a loop really slow?

    medium

    Since Java 9 a single concatenation expression compiles to an invokedynamic call (StringConcatFactory) that sizes the result in one go, so "a" + b + c is efficient. The problem remains in loops: each iteration builds a new string from the previous one, so n iterations copy O(n squared) characters. Use StringBuilder or String.join for loops.

  6. 6

    equals, equalsIgnoreCase, compareTo: how do they differ?

    easy

    equals checks exact content. equalsIgnoreCase ignores case with simple per-character folding. compareTo returns a negative, zero or positive int based on the first differing UTF-16 code unit, or on length difference if one string is a prefix of the other. Use compareTo for ordering and never assume the magnitude of its result.

    java
    System.out.println("apple".compareTo("banana")); // -1
    System.out.println("abc".compareTo("abcd"));     // -1  (length difference)
    System.out.println("b".compareTo("a"));          // 1
  7. 7

    How is String.hashCode computed, and why 31?

    medium

    It is s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], as an int that may overflow, cached in the object after the first call. 31 is an odd prime, and 31 * x can be computed as (x << 5) - x. Different strings can collide, for example "Aa" and "BB", which is why equals is still required.

  8. 8

    What is the gotcha with split?

    medium

    split takes a regular expression and removes trailing empty strings by default. A pipe or dot used as the delimiter must be escaped, otherwise it is treated as a regex metacharacter. A negative limit keeps trailing empties. An empty input returns an array with one empty string.

    java
    System.out.println("a,b,,".split(",").length);      // 2
    System.out.println("a,b,,".split(",", -1).length);  // 4
    System.out.println("".split(",").length);           // 1
    System.out.println(Arrays.toString("a|b".split("|")));   // [a, |, b]
    System.out.println(Arrays.toString("a|b".split("\\|"))); // [a, b]
  9. 9

    replace versus replaceAll: predict the output.

    medium

    replace(CharSequence, CharSequence) treats the target literally and replaces all occurrences. replaceAll treats its first argument as a regex, so "." matches every character. replaceFirst replaces only the first match.

    java
    System.out.println("a.b.c".replace(".", "-"));    // a-b-c
    System.out.println("a.b.c".replaceAll(".", "-"));  // -----
    System.out.println("a.b.c".replaceAll("\\.", "-")); // a-b-c
  10. 10

    Write a method to check whether a string is a palindrome, ignoring case and non-letters.

    easy

    Use two pointers, skipping characters that are not letters or digits. It runs in O(n) time and O(1) extra space. Avoid building a reversed copy unless the question allows it.

    java
    static boolean isPal(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
            while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
            if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--))) return false;
        }
        return true;
    }
    // isPal("A man, a plan, a canal: Panama") -> true
  11. 11

    Check whether two strings are anagrams in O(n).

    medium

    Count characters of the first string in an int array, subtract for the second and check that all counts are zero. For lowercase ASCII use int[26]; for general Unicode use a HashMap or work on code points. Sorting both is simpler but O(n log n).

    java
    static boolean anagram(String a, String b) {
        if (a.length() != b.length()) return false;
        int[] cnt = new int[26];
        for (int i = 0; i < a.length(); i++) {
            cnt[a.charAt(i) - 'a']++;
            cnt[b.charAt(i) - 'a']--;
        }
        for (int x : cnt) if (x != 0) return false;
        return true;
    }
  12. 12

    Why is char[] recommended over String for passwords?

    medium

    A String stays in memory, possibly in the pool, until garbage collected and cannot be wiped. A char[] can be overwritten with Arrays.fill right after use, which shortens the time the secret sits in memory. In practice, dump files and logs make this a partial mitigation, but it is why APIs like Console.readPassword return a char[].

  13. 13

    What do strip, trim, isBlank, repeat, lines and text blocks do?

    medium

    trim removes characters up to U+0020 only, while strip (Java 11) uses Character.isWhitespace and handles Unicode spaces. isBlank is true for empty or whitespace-only strings, unlike isEmpty. repeat(n) concatenates n copies and lines() streams the lines. A text block (Java 15) is delimited by triple quotes, keeps newlines, and strips incidental indentation based on the closing delimiter.

    java
    System.out.println("ab".repeat(3));        // ababab
    System.out.println("  ".isBlank());         // true
    String json = """
        {"id": 1}
        """;
    System.out.print(json);                    // {"id": 1} followed by a newline
  14. 14

    What are compact strings (Java 9)?

    hard

    Java 9 changed String storage from char[] to byte[] with a coder flag. If all characters fit in Latin-1 the string uses one byte per character, otherwise UTF-16 with two bytes. This cuts memory for typical English text, and length() and charAt still work in UTF-16 units. A character outside the Basic Multilingual Plane, such as an emoji, takes two chars (a surrogate pair), so length() counts 2 for it; use codePointCount for characters.

  15. 15

    Predict: what is the result of null concatenation and of switch on a null string?

    hard

    Concatenating a null String reference with + appends the text "null" and does not throw. A switch statement on a null String throws NullPointerException, because it calls hashCode (and then equals) on the selector. Guard against null before the switch.

    java
    String s = null;
    System.out.println(s + "x");        // nullx
    // switch (s) { case "a": ... }     // NullPointerException
  16. 16

    How do you reverse a string and count the occurrences of a character?

    easy

    StringBuilder.reverse handles surrogate pairs correctly. For counting, a loop is O(n), or chars().filter(...).count() for a stream version. Remember that reversing by index with charAt breaks emoji and other supplementary characters.

    java
    String s = "banana";
    System.out.println(new StringBuilder(s).reverse());          // ananab
    long n = s.chars().filter(ch -> ch == 'a').count();
    System.out.println(n);                                       // 3

Frequently asked questions

Why is String final?

Making the class final prevents subclasses from breaking immutability, which the pool, caching and security checks depend on.

What is the difference between a string literal and new String?

A literal comes from the pool and may be shared; new String always allocates a new object on the heap.

Is String thread safe?

Yes, because it is immutable. StringBuilder is not thread safe.

How many string questions appear in coding rounds?

Very commonly. Anagram, palindrome, longest substring and character frequency problems are frequent. See the DSA hub for practice.

Related guides

More in Programming Language Interview Questions by Language

See all in this section