1 · Foundations · lesson 5 of 41

Strings

Immutable text, the String pool, and how to concatenate efficiently.

String objects are immutable — every 'modification' creates a new object. Literals live in the String pool so identical literals share memory.

Java
String a = "Java";
String b = a + " 21";               // new object "Java 21"
String c = String.format("Hi %s!", a);

// Efficient repeated concatenation:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.append(i);
String result = sb.toString();

// Text blocks (Java 15+):
String json = """
    { "name": "Ada" }
    """;
Key takeaways
  • ✓Strings are immutable — reuse literals from the pool for equality.
  • ✓Use StringBuilder inside loops instead of += concatenation.
  • ✓Text blocks (""") preserve multi-line formatting.