JvJava
IntermediateLesson 7 of 16

Strings, StringBuilder & Text Blocks – Java

Processing and formatting text and writing multi-line text cleanly.

String is immutable: every method returns a new string. The most important methods:

String s = "  Java is fun  ";
System.out.println(s.strip().toLowerCase());        // java is fun
System.out.println(Arrays.toString("a,b,c".split(",")));   // [a, b, c]
System.out.println(String.join("-", "x", "y", "z")); // x-y-z
System.out.println("Java".replace('a', 'A'));       // JAvA
System.out.println("abc".startsWith("a") + " " + "ab".repeat(3));  // true ababab
System.out.println("   ".isBlank());                // true
System.out.println("Java".charAt(1) + " " + "Java".indexOf("v"));  // a 2

In loops, use a StringBuilder for many appends, otherwise countless intermediate strings are created. For output formats there are String.format and formatted.

var sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append(i).append(", ");
}
sb.setLength(sb.length() - 2);          // cut off the last ", "
System.out.println(sb);                 // 1, 2, 3
System.out.println(new StringBuilder("Java").reverse());   // avaJ

System.out.println(String.format("%-8s|%5d|%8.2f", "Ada", 36, 3.14159));
System.out.println("%s is %d years old".formatted("Ada", 36));

You write text blocks (Java 15+) with three quotation marks. They contain line breaks directly and need no escaping of ". The common indentation is removed automatically – the least indented line is what counts (including the line with the closing """).

String json = """
        {
          "name": "Ada",
          "alter": 36
        }
        """;
System.out.print(json);

String sql = """
        SELECT name, alter
        FROM person
        WHERE alter > %d
        """.formatted(30);
WarningNever compare strings with == (that checks the reference), but with equals: "abc".equals(eingabe). Put the constant on the left – then there is no NullPointerException if eingabe is null.