Strings, StringBuilder, text blocks

Core Java · lesson 6 of 42 · 4 min read

Compare strings correctly, build them efficiently, and write multi-line text without escapes.

Open this lesson in the learning hub

Key points

  • Strings are immutable. toUpperCase() returns a new String and leaves the original alone.
  • Compare with equals(). == asks "same object?" — true for pooled literals, false for new String("java").
  • Joining text with + inside a loop rebuilds the whole string each pass. Use StringBuilder there.
  • StringBuilder changes in place: append, insert, reverse, then toString() at the end.
  • Text blocks (""") hold multi-line text with no escaped quotes, and strip the shared left indentation.
  • Useful methods: strip(), isBlank(), repeat(), String.join(), formatted().

Example

public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = "ja" + "va";
        String c = new String("java");

        System.out.println("a == b      : " + (a == b) + "  (both are the pooled literal)");
        System.out.println("a == c      : " + (a == c) + " (new String makes a fresh object)");
        System.out.println("a.equals(c) : " + a.equals(c));

        System.out.println("upper: " + a.toUpperCase() + ", original still: " + a);
        System.out.println("strip: [" + "  hi  ".strip() + "], join: " + String.join("-", "x", "y", "z"));

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i).append(',');
        }
        sb.setLength(sb.length() - 1);
        System.out.println("built: " + sb + ", reversed in place: " + sb.reverse());

        String json = """
                {
                  "name": "Ada",
                  "roles": ["admin", "dev"]
                }""";
        System.out.println(json);

        System.out.println("""
                Hi %s, you have %d new messages.""".formatted("Ada", 3));
    }
}

Strings never change: equals() to compare, StringBuilder to build.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.