12.1 String Immutability, String Pool & Essential Methods
Key Takeaways
java.lang.Stringis final and immutable. A method such asconcat,replace, ortrimreturns the result while leaving the original contents unchanged.Equal string literals and string constant expressions are interned. A run-time concatenation or
new String(...)creates a distinct instance, andintern()returns the canonical instance.substring(begin, end)includesbeginand excludesend. Equal valid indices give an empty string, and invalid bounds causeIndexOutOfBoundsException.indexOfreturns-1when the search finds no match.charAtthrowsIndexOutOfBoundsExceptionfor an index outside0throughlength() - 1.replace(char, char) and replace(CharSequence, CharSequence) match literal text across all occurrences without regular expressions, and trim() removes leading and trailing characters <=
'\u0020'
Follow the String Value
java.lang.String is immutable, and equal literals are interned. When tracing a snippet, track the result of each method call and distinguish ==, which tests reference identity, from .equals(), which tests contents.
String Immutability and the final Class
The String class is declared public final class String in java.lang (which is imported automatically). Two guarantees follow from its design:
- Cannot be subclassed: Because
Stringisfinal, no class can extendStringto overrideequals,hashCode, orlengthand break immutability contracts. - State never changes after construction: Methods like
concat,toUpperCase,trim, andreplacereturn the result without changing the receiver. For example, the documented result of"Java".concat("")is the receiver itself.
The Discarded Return Value Trap
Calling a String method without capturing its return value is one of the most common exam traps:
String version = "Java";
version.concat(" SE 8"); // Creates "Java SE 8" and discards it
version.toUpperCase(); // Creates "JAVA" and discards it
System.out.println(version); // Prints: Java
version = version.concat(" 8"); // Reassigns reference to new String
System.out.println(version); // Prints: Java 8
Warning
A final String variable cannot be reassigned (version = ... fails compilation), whereas a non-final String variable can be reassigned to a different String object. The String object itself is always immutable; mutating the variable means pointing it to a new object.
String Pool vs. new String(...) and .intern()
To avoid duplicating identical character sequences in memory, the JVM maintains a String Pool (a table of canonical strings). How a String is created determines whether == compares to the same pooled object or a distinct heap object:
- String literals and compile-time constants (
"Java","Ja" + "va") are interned. Two references to identical literals satisfya == b(true). new String("Java")forces allocation of a freshStringobject on the heap outside the pool, even though the literal"Java"itself is in the pool.- Runtime concatenation involving a non-constant variable (
String prefix = "Ja"; String s = prefix + "va";) creates a distinct result at run time. A method call is not a constant expression, but its return identity depends on the method contract. .intern()checks the String Pool for an equalString. If found, it returns the pooled reference. Otherwise, it adds the receiver to the pool and returns the receiver.
String a = "Java";
String b = "Ja" + "va"; // Compile-time constant -> pooled
String part = "Ja";
String c = part + "va"; // Runtime concatenation -> heap
String d = new String("Java"); // Explicit constructor -> heap
String e = d.intern(); // Returns pooled "Java"
System.out.println(a == b); // true
System.out.println(a == c); // false
System.out.println(a == d); // false
System.out.println(a == e); // true
System.out.println(a.equals(c)); // true
System.out.println(a.equals(d)); // true
Tip
Remember left-to-right + operator associativity with String: 1 + 2 + "3" evaluates (1 + 2) + "3" and produces "33", whereas "1" + 2 + 3 evaluates ("1" + 2) + 3 and produces "123".
Method Chaining Evaluation
Because each transformation method returns a String, calls can be chained left to right. Each step invokes the next method on the temporary String produced by the previous step:
String raw = " Java ";
String cleaned = raw.trim() // "Java"
.toLowerCase() // "java"
.replace('a', 'o'); // "jovo"
System.out.println(raw); // " Java " (unchanged)
System.out.println(cleaned); // "jovo"
If a method in the chain returns int (such as length() or indexOf(...)) or boolean (such as startsWith(...)), chaining another String method afterward causes a compiler error because primitives have no methods.
Essential String Methods and Edge Cases
Java String indices are 0-based and count UTF-16 code units. A supplementary Unicode character uses two code units. For a string of length n, charAt accepts 0 through n - 1.
| Method Signature | Return Type | Core Behavior | Critical Edge Case / Exception |
|---|---|---|---|
length() | int | Returns the number of UTF-16 code units | Method with (), unlike array .length field; "".length() is 0 |
charAt(int index) | char | Returns char at index | index < 0 or index >= length() throws IndexOutOfBoundsException |
indexOf(int ch) | int | First index of Unicode code point ch, or -1 | Accepts char via widening; returns -1 if absent (never throws) |
indexOf(int ch, int fromIndex) | int | Searches forward starting at fromIndex | Negative fromIndex searches from 0; fromIndex >= length() returns -1 |
indexOf(String str) | int | First index of substring str, or -1 | s.indexOf("") returns 0; null throws NullPointerException |
indexOf(String str, int fromIndex) | int | Searches for str starting at fromIndex | "abc".indexOf("", 5) returns 3 (length()); absent str returns -1 |
substring(int beginIndex) | String | Slice from beginIndex to end | beginIndex == length() returns ""; < 0 or > length() throws IndexOutOfBoundsException |
substring(int begin, int end) | String | Slice [begin, end) (end exclusive) | begin == end returns "" for valid indices. A negative begin, reversed range, or end > length() throws IndexOutOfBoundsException. |
toLowerCase() / toUpperCase() | String | Converts case using default locale | Non-letter characters remain unchanged |
equals(Object obj) | boolean | Exact case-sensitive character match | Returns false for null or non-String arguments |
equalsIgnoreCase(String s) | boolean | Case-insensitive character match | Returns false if s is null |
startsWith(String prefix) | boolean | Case-sensitive prefix check | startsWith("") returns true; overloaded startsWith(prefix, offset) exists |
endsWith(String suffix) | boolean | Case-sensitive suffix check | endsWith("") returns true; null throws NullPointerException |
contains(CharSequence s) | boolean | true if s occurs anywhere inside | Case-sensitive; accepts StringBuilder; null throws NullPointerException |
replace(char oldChar, char newChar) | String | Replaces all oldChar with newChar | Returns this if oldChar is absent |
replace(CharSequence target, CharSequence rep) | String | Replaces all literal target occurrences | Does not use regex (unlike replaceAll); replaces left to right |
trim() | String | Strips leading/trailing chars <= '\u0020' | Removes spaces, '\t', '\n', '\r' at ends; leaves internal whitespace intact |
Tracing Tricky Edge Cases
Watch substring and indexOf combinations carefully:
String word = "animals";
System.out.println(word.substring(3)); // "mals"
System.out.println(word.substring(3, 3)); // "" (empty string, no exception)
System.out.println(word.substring(7)); // "" (begin == length() is valid)
System.out.println(word.indexOf('a', 1)); // 4 (skips index 0)
System.out.println(word.indexOf("al", 5)); // -1
System.out.println(word.replace("a", "X")); // "XnimXls"
// word.substring(4, 2); // StringIndexOutOfBoundsException
// word.substring(0, 8); // StringIndexOutOfBoundsException
// word.charAt(7); // StringIndexOutOfBoundsException
The Java SE 8 API for substring and charAt specifies IndexOutOfBoundsException. The usual JDK implementation throws the more specific subclass StringIndexOutOfBoundsException here. For an API-contract question, use the documented exception. For a catch-clause trace, a catch for the superclass also handles the subclass.
String padded = "\t Java 8 \n";
System.out.println("[" + padded.trim() + "]"); // [Java 8]
System.out.println("Java".contains(new StringBuilder("av"))); // true
Given the following Java SE 8 snippet, what is printed?
String s1 = "OCA";
String s2 = "O" + "CA";
String p = "O";
String s3 = p + "CA";
String s4 = new String("OCA").intern();
System.out.print((s1 == s2) + " " + (s1 == s3) + " " + (s1 == s4));
true true true
false false true
true false true
true false false
What is the result of executing the following code?
String text = " Java8 ";
String out = text.trim().substring(4, 4).concat("SE");
System.out.println(out.length() + ":" + out);
2:SE
3:8SE
0:
Throws IndexOutOfBoundsException at runtime
What is printed by the following Java SE 8 code?
String s = "banana";
s.replace('a', 'o');
int i = s.indexOf("na", 3);
System.out.println(s.substring(i) + ":" + s.startsWith("ba"));
ono:false
ono:true
na:false
na:true
Sections you finish are checked off in the contents.