The most common Java String questions in interviews and coding tests revolve around immutability, the difference between == and equals(), the String pool, and how to manipulate strings efficiently. This article answers those core questions in depth and covers related topics like StringBuilder, common pitfalls, and performance considerations.
What Makes String Immutable and Why Does It Matter?
In Java, String objects are immutable, meaning once a String object is created, its value cannot be changed. Any operation that appears to modify a string (like concat() or replace()) actually returns a new String object, leaving the original untouched.
This design is intentional and provides several benefits:
- Security: Strings are used extensively in networking, file paths, and class loading. Immutability prevents malicious code from altering a string reference after it has been validated.
- Thread safety: Immutable objects are inherently thread-safe; multiple threads can share a string without synchronization.
- String pool caching: Because strings are immutable, the JVM can safely cache them in the string constant pool, saving memory and improving performance.
- Hash code caching: The hash code of a string is computed once and cached, making strings excellent keys in hash-based collections like
HashMap.
A common misconception is that immutability means you cannot change a string variable. In fact, you can reassign a reference: String s = "hello"; s = s + " world"; creates a new string and points s to it. The original “hello” object remains in memory (until garbage collected).
How the String Pool Works
The String pool (also called the string constant pool) is a special area in the JVM heap where String literals are stored. When you write String s = "hello";, the JVM checks the pool first. If “hello” already exists, it reuses that reference; if not, it creates a new string in the pool.
Contrast this with the new keyword: String s = new String("hello"); always creates a new object on the heap, even if “hello” is already in the pool. This is why using new String() is generally discouraged—it wastes memory and defeats the purpose of the pool.
You can explicitly add a string to the pool using the intern() method: s.intern() returns the canonical representation from the pool. This is rarely needed in modern code but appears in older interview questions.
== vs .equals() – The Classic Trap
The == operator compares references (memory addresses), not content. The equals() method compares the actual characters. This distinction is the source of countless bugs and interview questions.
Example:
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true (both point to same pool object)
System.out.println(a == c); // false (c is a new object)
System.out.println(a.equals(c)); // true (content is equal)
Always use .equals() when comparing string content. For null-safe comparison, use Objects.equals(a, b) or "hello".equals(a) to avoid NullPointerException.
StringBuilder vs StringBuffer vs String
When you need to concatenate strings in a loop or build a large string, using + or concat() is inefficient because each operation creates a new object. The alternatives are:
- StringBuilder – Mutable, not thread-safe, but fastest. Recommended for single-threaded use.
- StringBuffer – Mutable and thread-safe (methods are synchronized), but slower due to locking. Rarely used today.
- String – Immutable, use for fixed content.
Example of efficient concatenation:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result = sb.toString();
In modern Java (8+), the compiler often converts + concatenation into StringBuilder operations automatically, but explicit use is still clearer and avoids surprises.
Common String Pitfalls and How to Avoid Them
Several String-related bugs appear frequently in production code:
- Using
==instead of.equals()– Already covered; always use.equals(). - Ignoring case sensitivity –
equals()is case-sensitive. UseequalsIgnoreCase()when needed. - Not handling null – Calling methods on a null string throws
NullPointerException. UseString.valueOf()or check for null first. - Memory leaks with
substring()(pre-Java 7) – In older Java versions,substring()kept a reference to the original string, causing memory leaks. This was fixed in Java 7, but be aware if you support legacy code. - Using
Stringfor mutable data – If you need to modify a string repeatedly, useStringBuilderto avoid creating many objects. - Locale-dependent methods –
toLowerCase()andtoUpperCase()use the default locale, which can cause bugs in Turkish or other locales. Use the overload withLocale.ROOTfor consistent behavior.
Performance and Memory Considerations
Strings are objects, and each one carries overhead (object header, char array, hash). In large applications, strings can dominate memory usage. Key points:
- String interning – The pool helps reuse literal strings, but
intern()on dynamic strings can cause memory pressure if overused. - Compact Strings (Java 9+) – The JVM stores strings as byte arrays when possible (ISO-8859-1) instead of UTF-16 char arrays, reducing memory usage by about half for many strings.
- Avoid concatenation in loops – Even with compiler optimizations, explicit
StringBuilderis clearer and avoids hidden allocations. - Use
String.valueOf()for conversions – It handles null gracefully, returning “null” instead of throwing.
For extremely large text processing, consider char[] or byte[] directly, though this is rarely necessary.
Frequently Asked Questions
Why is String immutable in Java?
Immutability provides security (prevents tampering), thread safety, and enables the string pool for memory efficiency. It also allows hash codes to be cached, making strings ideal for hash-based collections.
What is the difference between String, StringBuilder, and StringBuffer?
String is immutable; StringBuilder is mutable and not thread-safe; StringBuffer is mutable and thread-safe (synchronized). Use StringBuilder for most single-threaded concatenation, StringBuffer only if you need thread safety (rare).
How do you reverse a string in Java?
The simplest way is new StringBuilder(str).reverse().toString(). For older Java versions without StringBuilder, you can loop backward and build a char array, but StringBuilder is the standard answer.
What does String.intern() do?
It returns the canonical representation of the string from the string pool. If the string is already in the pool, it returns that reference; otherwise, it adds the string to the pool and returns the new reference. It’s rarely needed in modern code.
Is String a primitive or an object?
String is a class, not a primitive. It is an object that wraps a char array. However, it has special language support (like literals and the + operator) that makes it behave somewhat like a primitive.
How can I split a string by multiple delimiters?
Use String.split() with a regex. For example, "a,b;c".split("[,;]") splits on comma or semicolon. Remember that split() takes a regex, so special characters need escaping (e.g., \. for a dot).
Alternatives to String
While String is ubiquitous, there are alternatives for specific use cases:
- char[] – For security-sensitive data like passwords, char arrays are preferred because they can be cleared after use, whereas strings remain in memory until GC.
- StringBuilder / StringBuffer – For mutable strings.
- byte[] – For binary data or when encoding is known (e.g., UTF-8).
- java.util.StringJoiner – For joining sequences with delimiters, especially with streams.
- Text blocks (Java 15+) – For multi-line strings, using triple quotes:
""" ... """.
Choosing the right type depends on mutability, memory, and security requirements.
Related
- How to Select All Files in a Windows Folder (4 Ways)
- Multiple Imports on One Line? Python Style Guide
- Google Sheets Conditional Formatting Formula Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Cell Counting Techniques: Hemocytometer, Automated, and MoreCell counting techniques fall into two broad categories: manual counting with a hemocytometer and automated counting using instruments…
- How to Double Space in Word for the WebTo double-space text in Word for the web, select the text, open Home > Line and Paragraph Spacing,…
- Can You Hide Tabs in Excel? Sheets, Steps, and LimitsYes. In Excel for Microsoft 365 on Windows, right-click a worksheet tab and choose Hide to conceal that…
- Print an Excel Column on Every Page: Step-by-StepTo print the same Excel column on every printed page, open the worksheet and choose Page Layout >…
- How to Insert an Image Into a Cell in Excel ProperlyIn Excel for Microsoft 365 on Windows, select a cell, then choose Insert > Pictures > Place in…
- What Is a Range in Google Sheets? Meaning and ExamplesA range in Google Sheets is one cell or a group of cells identified by their addresses. For…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.