Java Tutorial: Strings & StringBuilder
Master Java String methods, String.format, StringBuilder for efficient building, and the String pool.
Strings are immutable — and that changes everything
In Java, `String` objects cannot be changed. Every time you concatenate or modify, Java creates a new String object. For a few operations, that's fine. For building strings in a loop — use `StringBuilder`.
This chapter covers everything from basic methods to efficient string building patterns you'll use in every real Java program.
What you'll learn in this Java strings & stringbuilder tutorial
This interactive Java tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Essential String methods — String has a huge API. The ones you'll use every day:
- substring and indexOf — Extract parts of a string:
- replace and split — - `.replace(old, new)` — replace all occurrences (strings)
- String.format — clean formatting — `String.format()` is like printf from C — use placeholders:
- equals vs == — the critical distinction — This is Java's most common beginner trap:
- StringBuilder — efficient string building — Strings are immutable — `s = s + "more"` creates a new String object each time. In a loop this is slow and wasteful.
- StringBuilder methods — `StringBuilder` has more than just append:
- Build a password validator — Final challenge — no starter code.
Java Strings & StringBuilder concepts covered
- Strings are immutable — and that changes everything