Memra

Strings, immutability & text blocks

The most-used reference type and why == is a trap.

Strings are objects — and immutable

A String is a reference type, not a primitive, and it is immutable: every method that "changes" a String actually returns a new one. s.toUpperCase() doesn't touch s.

Because Strings are immutable, Java keeps a String pool: identical literals share one object. That's why you must compare String contents with .equals(...), never == (which compares references):

String a = "hi";
String b = "hi";
a == b;        // true here by luck (pooled), but DON'T rely on it
a.equals(b);   // true — the correct way

Useful methods: length(), charAt(i), substring(a, b), indexOf(x), toUpperCase(), trim()/strip(), replace(a, b), isBlank(), contains(x).

Text blocks (Java 15+) write multi-line strings cleanly with """:

String json = """
    {"name": "Ada"}
    """;
NORMAL ~/memra/learn/java-from-zero/strings-and-text-blocks utf-8 LF