12.1 String Immutability, String Pool & Essential Methods

Key Takeaways

  • java.lang.String is final and immutable. A method such as concat, replace, or trim returns 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, and intern() returns the canonical instance.

  • substring(begin, end) includes begin and excludes end. Equal valid indices give an empty string, and invalid bounds cause IndexOutOfBoundsException.

  • indexOf returns -1 when the search finds no match. charAt throws IndexOutOfBoundsException for an index outside 0 through length() - 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'

Last updated: November 2026

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:

  1. Cannot be subclassed: Because String is final, no class can extend String to override equals, hashCode, or length and break immutability contracts.
  2. State never changes after construction: Methods like concat, toUpperCase, trim, and replace return 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 satisfy a == b (true).
  • new String("Java") forces allocation of a fresh String object 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 equal String. 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 SignatureReturn TypeCore BehaviorCritical Edge Case / Exception
length()intReturns the number of UTF-16 code unitsMethod with (), unlike array .length field; "".length() is 0
charAt(int index)charReturns char at indexindex < 0 or index >= length() throws IndexOutOfBoundsException
indexOf(int ch)intFirst index of Unicode code point ch, or -1Accepts char via widening; returns -1 if absent (never throws)
indexOf(int ch, int fromIndex)intSearches forward starting at fromIndexNegative fromIndex searches from 0; fromIndex >= length() returns -1
indexOf(String str)intFirst index of substring str, or -1s.indexOf("") returns 0; null throws NullPointerException
indexOf(String str, int fromIndex)intSearches for str starting at fromIndex"abc".indexOf("", 5) returns 3 (length()); absent str returns -1
substring(int beginIndex)StringSlice from beginIndex to endbeginIndex == length() returns ""; < 0 or > length() throws IndexOutOfBoundsException
substring(int begin, int end)StringSlice [begin, end) (end exclusive)begin == end returns "" for valid indices. A negative begin, reversed range, or end > length() throws IndexOutOfBoundsException.
toLowerCase() / toUpperCase()StringConverts case using default localeNon-letter characters remain unchanged
equals(Object obj)booleanExact case-sensitive character matchReturns false for null or non-String arguments
equalsIgnoreCase(String s)booleanCase-insensitive character matchReturns false if s is null
startsWith(String prefix)booleanCase-sensitive prefix checkstartsWith("") returns true; overloaded startsWith(prefix, offset) exists
endsWith(String suffix)booleanCase-sensitive suffix checkendsWith("") returns true; null throws NullPointerException
contains(CharSequence s)booleantrue if s occurs anywhere insideCase-sensitive; accepts StringBuilder; null throws NullPointerException
replace(char oldChar, char newChar)StringReplaces all oldChar with newCharReturns this if oldChar is absent
replace(CharSequence target, CharSequence rep)StringReplaces all literal target occurrencesDoes not use regex (unlike replaceAll); replaces left to right
trim()StringStrips 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
Loading diagram...
String Pool References vs. Separate Heap String Objects
Test Your Knowledge

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));
A

true true true

B

false false true

C

true false true

D

true false false

Test Your Knowledge

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);
A

2:SE

B

3:8SE

C

0:

D

Throws IndexOutOfBoundsException at runtime

Test Your Knowledge

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"));
A

ono:false

B

ono:true

C

na:false

D

na:true

Sections you finish are checked off in the contents.