String Immutability and the String Pool
Understand why Strings are immutable, how the string pool works, and when to use == vs equals.
String Immutability and the String Pool
Strings are immutable in Java. Understanding immutability, the string pool, and reference equality vs value equality prevents subtle bugs.
Why Strings are Immutable
String objects cannot be modified after creation. Any operation that "changes" a String actually creates a new String object. This enables sharing, thread-safety, and hashCode caching.
String s = "hello";
s.toUpperCase(); // creates a new String, does NOT modify s
System.out.println(s); // still "hello"
String upper = s.toUpperCase(); // must capture the result
System.out.println(upper); // HELLOAll lessons in this course
- String Immutability and the String Pool
- StringBuilder for Efficient Concatenation
- Text Blocks and String.format
- Regular Expressions with Pattern and Matcher