Java Notes
Comprehensive collection of Java String interview questions covering conceptual, coding, output prediction, and tricky questions asked in technical interviews at all levels.
This comprehensive collection covers the most frequently asked Java String interview questions organized by difficulty level and topic.
Section 1: Fundamental Conceptual Questions
Q1: What is a String in Java?
Answer: String is a class in java.lang package that represents an immutable sequence of characters. It is declared as public final class String and implements Serializable, Comparable<String>, and CharSequence interfaces. Strings are objects stored in heap memory, with literals benefiting from the String Pool.
Q2: Why is String immutable in Java?
Answer: String is immutable for five key reasons:
- String Pool sharing — Multiple variables can safely reference the same pool object
- Security — Strings used in network connections, file paths, and class loading can't be maliciously altered
- Thread safety — Immutable objects are inherently thread-safe without synchronization
- HashCode caching — Since content never changes, hashCode is computed once and reused
- Class loading — JVM uses strings for class names; mutable strings would compromise classloading security
Q3: What is the String Pool?
Answer: The String Pool (String Constant Pool) is a special memory area inside the heap (since Java 7) that stores unique string literals. When you create a literal like "Hello", JVM checks if this string exists in the pool:
- If yes → returns the existing reference (no new object)
- If no → creates a new string in the pool
This saves memory by sharing identical strings. Only string literals and intern()'d strings are in the pool.
Q4: Explain == vs .equals() for Strings.
Answer:
==compares references (memory addresses) — true only if both variables point to the exact same object.equals()compares content (character by character) — true if both strings have identical characters
String a = "Hello"; // Pool
String b = "Hello"; // Same pool object
String c = new String("Hello"); // New heap object
a == b; // true (same pool object)
a == c; // false (different objects)
a.equals(c); // true (same content)Rule: Always use .equals() for content comparison.
Q5: How many objects are created by String s = new String("Hello")?
Answer: Up to 2 objects:
- "Hello" in String Pool — created from the literal (if not already present)
- New String object in heap — created by the
newkeyword (always)
The variable s references the heap object (#2), not the pool object.
Q6: What is the intern() method?
Answer: intern() returns the canonical (pool) representation of a string:
- If the string exists in the pool → returns the pool reference
- If not → adds it to the pool and returns that reference
String s1 = new String("Hello"); // Heap object
String s2 = s1.intern(); // Pool reference
String s3 = "Hello"; // Pool reference
System.out.println(s2 == s3); // trueQ7: What is the difference between String, StringBuffer, and StringBuilder?
Answer:
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes (immutable) | Yes (synchronized) | No |
| Performance | Slow for modifications | Medium | Fast |
| Storage | String Pool + Heap | Heap | Heap |
| Since | JDK 1.0 | JDK 1.0 | JDK 1.5 |
| Use case | Constants, keys | Multi-threaded building | Single-threaded building |
Q8: Why is String final?
Answer: The final modifier on String class:
- Prevents subclassing — no class can extend String and override methods
- Preserves immutability — a subclass could add mutable state, breaking guarantees
- Enables JVM optimizations — compiler knows methods won't be overridden
- Security — ensures String behavior is predictable and unalterable
Q9: Can we use String in switch statements?
Answer: Yes, since Java 7. Strings in switch use .equals() internally:
The switch compares using equals() and hashCode() for efficiency.
Q10: What is the String.format() method?
Answer: A static method that creates formatted strings using format specifiers:
%s— String%d— Integer%f— Float/Double (%.2f for 2 decimal places)%c— Character%b— Boolean%n— Platform-specific newline
String result = String.format("Name: %s, Age: %d, GPA: %.2f", "Alice", 25, 3.85);
// "Name: Alice, Age: 25, GPA: 3.85"Section 2: Output Prediction Questions
Q11: What is the output?
public class Output1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}true false true
Explanation: s1 and s2 share the same pool object. s3 is a separate heap object. .equals() compares content.
Q12: What is the output?
public class Output2 {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Ja" + "va";
String s3 = "Ja";
String s4 = s3 + "va";
System.out.println(s1 == s2);
System.out.println(s1 == s4);
System.out.println(s1.equals(s4));
}
}true false true
Explanation: "Ja" + "va" is computed at compile time (constant folding) → same as "Java" in pool. But s3 + "va" involves a variable, so it's computed at runtime using StringBuilder → new heap object.
Q13: What is the output?
public class Output3 {
public static void main(String[] args) {
String s = "Hello";
s.toUpperCase();
s.concat(" World");
System.out.println(s);
}
}Hello
Explanation: String is immutable. toUpperCase() and concat() return NEW strings, but the results are not assigned back to s. The original s remains "Hello".
Q14: What is the output?
public class Output4 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = s2.intern();
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s2 == s3);
}
}false true false
Explanation: s2 is a heap object. s3 = s2.intern() returns the pool reference (same as s1). So s1 == s3 is true, but s2 is still the separate heap object.
Q15: What is the output?
public class Output5 {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
System.out.println(s1.hashCode() == s2.hashCode());
System.out.println(System.identityHashCode(s1) == System.identityHashCode(s2));
}
}true true
Explanation: Both have same content so same hashCode. And since both are from pool, they're the same object — so identityHashCode (which is based on object identity) is also the same.
Q16: What is the output?
public class Output6 {
public static void main(String[] args) {
String str = null;
System.out.println("null".equals(str));
System.out.println(str.equals("null"));
}
}false Exception in thread "main" java.lang.NullPointerException
Explanation: "null".equals(str) safely returns false (comparing "null" content with null reference). But str.equals("null") calls a method on null → NullPointerException.
Best Practice: Put the literal on the left: "expected".equals(variable).
Section 3: Coding Questions
Q17: How to count occurrences of a character in a string?
public class CharCount {
public static void main(String[] args) {
String str = "Hello World";
char target = 'l';
long count = str.chars().filter(c -> c == target).count();
System.out.println("'" + target + "' appears " + count + " times in \"" + str + "\"");
}
}'l' appears 3 times in "Hello World"
Q18: Write a program to check if a string is a valid email.
user@example.com → Valid invalid@ → Invalid @domain.com → Invalid user.name@domain.co.in → Valid no-at-sign → Invalid
Q19: Find all permutations of a string.
Permutations of "ABC": ABC ACB BAC BCA CBA CAB
Q20: Longest common prefix among an array of strings.
Strings: [flower, flow, flight] Longest common prefix: "fl"
Section 4: Advanced Questions
Q21: How does String concatenation work internally?
Answer: The + operator for strings is compiled to StringBuilder operations:
// Source code:
String result = "Hello" + " " + name + "!";
// Compiled to (approximately):
String result = new StringBuilder()
.append("Hello").append(" ").append(name).append("!")
.toString();Exception: If ALL operands are compile-time constants (literals or final variables), the compiler performs concatenation at compile time (constant folding).
Q22: What is the difference between String.valueOf() and Object.toString()?
Answer:
String.valueOf(null)→ returns the String"null"(safe)null.toString()→ throwsNullPointerExceptionString.valueOf(obj)internally callsobj.toString()but handles null
Q23: Why shouldn't we use String as a password storage?
Answer:
- Strings are immutable — cannot be cleared from memory after use
- Strings may reside in String Pool for extended periods
- String content appears in heap dumps
- Use char[] instead — can be zeroed out after use:
Arrays.fill(password, '0')
Q24: How is String hashCode calculated?
Answer: Using the formula: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
31 is used because: it's a prime (reduces collisions), it's odd (avoids overflow issues with even numbers), and 31 * x can be optimized to (x << 5) - x by the JIT compiler.
Q25: What are compact strings (Java 9+)?
Answer: Before Java 9, Strings stored characters in a char[] (2 bytes per character). Since Java 9, strings that contain only Latin-1 characters use a byte[] with 1 byte per character (LATIN1 encoding). Strings with other characters use 2 bytes per character (UTF-16). This reduces memory usage by approximately 30-40% for typical applications.
Common Mistakes
- Using == for content comparison — always returns wrong results for non-literal strings
- Not assigning method results —
s.trim()withouts = s.trim() - Calling methods on null — always check or put literal first
- String concatenation in loops — use StringBuilder
- Ignoring case sensitivity — use equalsIgnoreCase when appropriate
- Not understanding String Pool — leads to confusion about == behavior
Best Practices
- Always use .equals() for String comparison
- Put literals first in equals:
"text".equals(variable) - Use StringBuilder for repeated concatenation
- Use String.isEmpty() or isBlank() instead of
s.equals("") - Consider StringJoiner or String.join() for joining collections
- Use char[] for passwords — not String
- Set initial StringBuilder capacity when size is known
- Use switch on Strings (Java 7+) instead of if-else chains
- Prefer String.format() for complex formatting
- Understand intern() but don't overuse it — let the JVM manage the pool
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for String Interview Questions.
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