beginnerFree

Strings

Immutable text - the most-used Java type

Strings

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).

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:17

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 a String object
  • 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 += part in a loop builds a new String each time (literals are folded)
  • StringBuilder is 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
  • StringBuffer is thread-safe but slower than StringBuilder

Pitfalls and Best Practices

  • Use equals() not == to compare string content
  • Use StringBuilder for concatenation in loops
  • Avoid new String("literal") - wastes memory
  • Calling a method on a null reference throws NullPointerException; 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
#java#fundamentals#strings