beginnerFree
Strings
Immutable text - the most-used Java type

Strings are objects, not primitives. They're immutable - operations never change the original; text-transform methods return a new string, while query methods return non-string results (int/char/boolean).
Watch
The narrated version of this skribble — tap play for the full-size video.
0:00 / 1:17
Deep dive
The Big Picture
Strings represent immutable text in Java.
- The most commonly used type after
int - Objects, not primitives - stored on the heap
- Literal syntax:
"Hello"creates aStringobject - Immutable - original never changes; transform→new String, query→int/char/bool
Used everywhere: user input, file content, network data.
How It Works
Strings are backed by a char[] (Java 8) or byte[] (Java 9+). Because they're immutable, they're thread-safe and cacheable.
result += partin a loop builds a new String each time (literals are folded)StringBuilderis mutable - use for building strings in loops- String pool caches literals to save memory
equals()compares content; == compares references
In the Java Landscape
Strings evolved significantly across Java versions.
- Java 9: compact strings (Latin-1 uses 1 byte per char)
- Java 11:
isBlank(),strip(),lines(),repeat() - Java 15: text blocks (preview in 13/14) with triple quotes
"""...""" - Java 15:
formatted()instance method StringBufferis thread-safe but slower thanStringBuilder
Pitfalls and Best Practices
- Use
equals()not == to compare string content - Use
StringBuilderfor concatenation in loops - Avoid
new String("literal")- wastes memory - Calling a method on a
nullreference throwsNullPointerException; concatenation converts null to "null" - Use
String.format()or text blocks for complex strings - Use equals() for content; intern() only for rare dedupe/symbol tables



