Java Interview Preparation
Strings Interview Questions
String immutability, pooling, StringBuilder, equality, and text processing.
Strings Interview Focus
String immutability, pooling, StringBuilder, equality, and text processing.
Interview questions
1. What is a String in Java? Beginner
A String is an object that represents a sequence of characters and belongs to java.lang, which Java imports automatically. Strings can contain letters, numbers, spaces, symbols, and Unicode characters. The String class is final and immutable, so an operation that appears to change a value actually returns another String object. String literals may be stored and reused through the String Constant Pool.
String name = "Anand";
String message = "Welcome to Java";
System.out.println(message);2. Why are strings immutable in Java? Beginner
String immutability means the characters in a String object cannot change after construction. Methods such as concat and replace return a new String instead of changing the original. This makes strings safe to share between threads, allows pooled literals to be reused, keeps hash codes stable when strings are HashMap keys, and helps protect values such as class names and URLs from unexpected modification. A reference variable can point to a new String, but the old object is still unchanged.
3. What is the Java String Constant Pool? Intermediate
The String Constant Pool is a JVM-managed area in the heap that stores reusable string literals and interned strings. When the same literal is used more than once, the JVM can reuse one object instead of allocating duplicates. This is why two literal references may be identical with ==, although equals should be used to compare string content. The pool improves reuse, but dynamically interning many unique values can increase memory pressure.
4. What is the difference between creating a string using a literal and using the new keyword? Beginner
A literal such as String value = "Java" checks the String Pool and reuses the pooled object when possible. new String("Java") explicitly creates another String object on the heap, even though the literal may also exist in the pool. Literals are normally more memory-efficient and are preferred. Use equals for content comparison because == compares references.
String first = "Java";
String second = "Java";
String third = new String("Java");
System.out.println(first == second); // true
System.out.println(first.equals(third)); // true5. What is the difference between == and equals() when comparing strings? Beginner
The == operator compares object references, meaning it checks whether two variables point to the same object. equals compares the characters contained in the strings. Use equals or equalsIgnoreCase when the business requirement is value comparison. A null-safe style is "Java".equals(language), because the literal cannot be null.
String first = "Java";
String second = new String("Java");
System.out.println(first == second); // false
System.out.println(first.equals(second)); // true6. What is the difference between String, StringBuilder, and StringBuffer? Beginner
String is immutable and is best for values that do not change frequently. StringBuilder is mutable and is usually the best choice for repeated changes in one thread. StringBuffer is also mutable but synchronizes its methods, so it can be useful when the same instance is genuinely shared between threads, although a design with separate builders or other coordination is often better. Repeated String concatenation creates more temporary objects.
7. Why is StringBuilder faster than StringBuffer? Intermediate
StringBuilder methods are not synchronized, so they avoid the locking overhead that StringBuffer adds for thread-safe access. This usually makes StringBuilder faster in local, single-threaded operations such as building a response in one method. StringBuilder is not safe for unsynchronized concurrent mutation. Choose StringBuffer only when shared mutable text truly needs its synchronized methods; immutable String or separate builders are often safer alternatives.
8. Is the String class thread-safe? Intermediate
Yes. String is effectively thread-safe because it is immutable: once created, its character data cannot change. Multiple threads can safely read and share the same String without synchronization. A shared variable that points to a String can still be reassigned by different threads, so visibility or coordination may be needed for that variable; immutability protects the object, not every update to a reference.
9. What does the intern() method do in Java? Intermediate
intern returns the canonical pooled representation of a string. If a matching value exists in the String Pool, intern returns that reference; otherwise the value is added or located there. For example, new String("Java").intern() can refer to the same pooled object as the literal "Java". Interning can reduce duplicates in carefully controlled data, but interning a large number of unique values may increase pool memory and lookup overhead.
10. How does the concat() method work with immutable strings? Beginner
concat returns a String containing the original value followed by the supplied value. It does not modify the original object, so the returned value must be stored or assigned back. If the supplied string is empty, concat may return the original string. For many concatenations in a loop, use StringBuilder instead of repeatedly calling concat.
String value = "Java";
value.concat(" Programming");
System.out.println(value); // Java
value = value.concat(" Programming");
System.out.println(value); // Java Programming11. What is the difference between isEmpty(), isBlank(), and checking length() == 0? Beginner
isEmpty and length() == 0 both return true only when the string has zero characters. isBlank, available since Java 11, also returns true for a string containing only whitespace such as spaces, tabs, or line breaks. None of these methods accepts a null reference, so check for null first or use a suitable validation utility.
String username = " ";
if (username == null || username.isBlank()) {
System.out.println("Username is required");
}12. What is the difference between substring(), subSequence(), and split()? Intermediate
substring returns part of a String, with the start index inclusive and the end index exclusive. subSequence extracts the same kind of range but returns CharSequence. split divides the value into a String array using a regular-expression delimiter. Because split uses regular expressions, a literal dot must be escaped as "\.". Invalid indexes for substring or subSequence cause an index-related exception.
13. How can you reverse a string in Java? Beginner
The simplest approach is new StringBuilder(value).reverse().toString(). For an interview, you can also loop from the last index to zero and append each character to a StringBuilder. Both approaches create a new result because String itself is immutable. Handle null according to the application contract before attempting the reversal.
String value = "Java";
String reversed = new StringBuilder(value).reverse().toString();
System.out.println(reversed); // avaJ14. How can you check whether a string is a palindrome? Intermediate
A palindrome reads the same from left to right and right to left. Compare characters from both ends with two pointers and move them toward the middle; return false on the first mismatch. For a case-insensitive phrase, normalize case and optionally remove spaces and punctuation before comparing. This two-pointer method uses O(n) time and O(1) extra space after normalization.
static boolean isPalindrome(String value) {
int left = 0, right = value.length() - 1;
while (left < right) {
if (value.charAt(left++) != value.charAt(right--)) return false;
}
return true;
}15. How can you count duplicate characters in a string? Intermediate
Use a Map<Character, Integer> and increase the count for every character. After counting, keep entries whose value is greater than one. LinkedHashMap is useful when the output should preserve the order in which characters first appeared. Decide whether spaces, case differences, and Unicode code points should be treated as distinct before writing the loop.
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char character : value.toCharArray()) {
counts.merge(character, 1, Integer::sum);
}16. How can you find the first non-repeated character in a string? Intermediate
Count each character in a LinkedHashMap, then iterate through the map in insertion order and return the first entry whose count is one. LinkedHashMap matters because a normal HashMap does not promise the original order. If no character appears once, return an empty Optional or another result that clearly represents “not found”.
17. How can you check whether two strings are anagrams? Intermediate
Two strings are anagrams when they contain the same characters with the same frequencies, regardless of order. Normalize them according to the requirement, for example by removing spaces and converting to lower case. Then either sort both character arrays and compare them or count characters in one map or array and subtract counts from the other. Sorting is easier to explain; counting can be more efficient for a known character range.
char[] firstCharacters = first.toLowerCase().toCharArray();
char[] secondCharacters = second.toLowerCase().toCharArray();
Arrays.sort(firstCharacters);
Arrays.sort(secondCharacters);
return Arrays.equals(firstCharacters, secondCharacters);18. How can you remove duplicate characters from a string? Intermediate
Use a LinkedHashSet to store each character once and preserve its first-seen order, then append the set contents to a StringBuilder. For example, programming becomes progamin. A boolean array or a map can be used when the character range is known. Decide whether duplicate detection should be case-sensitive and whether whitespace should be preserved.
Set<Character> unique = new LinkedHashSet<>();
for (char character : value.toCharArray()) unique.add(character);
StringBuilder result = new StringBuilder();
for (char character : unique) result.append(character);
return result.toString();19. How are strings stored in JVM memory? Advanced
String objects are stored in heap memory. String literals and interned values are managed through the String Pool, which is also in the heap in modern JVMs. Local variables hold references from stack frames; they do not contain the complete object itself. new String creates a separate object, while a literal can reuse a pooled object. Many unique dynamic strings, large payloads, unbounded caches, or excessive logging can increase heap pressure.
20. What are the performance problems caused by repeated string concatenation inside a loop? Advanced
Because String is immutable, repeated concatenation can create a new object and copy existing characters on every iteration. This increases allocations, copying, CPU work, and garbage-collection pressure, and can approach O(n²) time for a growing result. Use StringBuilder for repeated single-threaded appends, StringBuffer only for a genuine shared-mutation requirement, and String.join or Collectors.joining for collections. Providing an estimated StringBuilder capacity can reduce resizing.
StringBuilder builder = new StringBuilder();
for (String name : names) {
builder.append(name);
}
String result = builder.toString();How to Prepare for Java Technical Interviews
Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.
Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.
Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.
