← Back to Java series
πŸ’Ύ
Exceptions & I/O
Exceptions & I/O Β· Prerequisite: previous lecture

17. Strings and Text Blocks

String manipulation, the `StringBuilder` for efficient mutation, multi-line text blocks (JDK 15+), and `String.format` / `formatted`.

JavaStringStringBuildertext block
Duration
⏱ ~1-1.5 hours
Level
πŸ“Š Beginner-Intermediate
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
String manipulation, the `StringBuilder` for efficient mutation, multi-line text blocks (JDK 15+), and `String.format` / `formatted`.

What you'll learn

  • 1Use the common `String` methods
  • 2Concatenate efficiently with `StringBuilder`
  • 3Use multi-line text blocks (`"""`) β€” JDK 15+
  • 4Format strings with `String.format` / `formatted`

Overview

String manipulation, the `StringBuilder` for efficient mutation, multi-line text blocks (JDK 15+), and `String.format` / `formatted`.

Core Concepts

1) Common `String` methods

java
String s = "  Hello, Java!  ";
System.out.println(s.length());
System.out.println(s.trim());
System.out.println(s.toUpperCase());
System.out.println(s.contains("Java"));
System.out.println(s.replace("Java", "World"));
System.out.println(s.split(",")[0]);

2) `StringBuilder`

Strings are **immutable**. Repeated concatenation in a loop allocates a fresh `String` each time. Use `StringBuilder` for efficient mutation.

java
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append("#").append(i);
String result = sb.toString();   // #0#1#2#3#4

3) Text blocks (JDK 15+)

java
String json = """
        {
          "name": "Jisoo",
          "age": 21
        }
        """;

Indentation is auto-aligned to the closing `"""`.

4) `String.format` and `formatted`

java
String s1 = String.format("name=%s, age=%d", "Jisoo", 21);
String s2 = "name=%s, age=%d".formatted("Jisoo", 21);   // JDK 15+

5) `String.join`

java
String csv = String.join(",", "a", "b", "c");   // a,b,c

Examples

Example 1 β€” `Common.java`

java
public class Common {
    public static void main(String[] args) {
        String s = "Hello, Java!";
        System.out.println("length=" + s.length());
        System.out.println("upper=" + s.toUpperCase());
        System.out.println("contains Java? " + s.contains("Java"));
        System.out.println("replace=" + s.replace("Java", "World"));
    }
}

**Output**

text
length=12
upper=HELLO, JAVA!
contains Java? true
replace=Hello, World!

Example 2 β€” `StringBuilderDemo.java`

java
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) sb.append("#").append(i);
        System.out.println(sb);
        System.out.println("length=" + sb.length());
        sb.reverse();
        System.out.println("reversed=" + sb);
    }
}

**Output**

text
#0#1#2#3#4
length=10
reversed=4#3#2#1#0#

Example 3 β€” `TextBlock.java`

java
public class TextBlock {
    public static void main(String[] args) {
        String json = """
                {
                  "name": "Jisoo",
                  "age": 21
                }
                """;
        System.out.println(json);
    }
}

**Output**

text
{
  "name": "Jisoo",
  "age": 21
}

Example 4 β€” `FormatDemo.java`

java
public class FormatDemo {
    public static void main(String[] args) {
        String s = String.format("name=%s, age=%d, score=%.2f", "Jisoo", 21, 92.5);
        System.out.println(s);

        String s2 = "Hello, %s!".formatted("World");
        System.out.println(s2);
    }
}

**Output**

text
name=Jisoo, age=21, score=92.50
Hello, World!

Common Mistakes

  1. Concatenating in tight loops with `+` instead of `StringBuilder`
  2. Comparing strings with `==` instead of `.equals()`
  3. Forgetting that `split` takes a regex (so `split(".")` matches everything)
  4. Indentation mistakes in a text block leaking leading spaces
  5. Confusing `String.format` (returns a String) with `System.out.printf` (prints directly)

Summary

  • `String` is immutable β€” every operation produces a new one
  • Mutate with `StringBuilder`
  • Text blocks (`"""`) make multi-line literals readable
  • `String.format` / `formatted` make typed formatting safer than `+`

Practice

# Practice - 17. Strings

## Exercise 1 β€” Reverse a sentence

  • File: `Homework01.java`
  • Key concepts: `split`, `StringBuilder`

Requirements

  • Reverse the word order of `"Hello brave new world"`.

Expected output

text
world new brave Hello

## Exercise 2 β€” Render a CSV

  • File: `Homework02.java`
  • Key concepts: `String.join`, text block

Requirements

  • Build the CSV `name,age\nJisoo,21\nMinsu,25\n` using a text block or `String.format`.

Expected output

text
name,age
Jisoo,21
Minsu,25

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
/** Reverse word order. */
public class Homework01 {
    public static void main(String[] args) {
        String s = "Hello brave new world";
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]);
            if (i > 0) sb.append(' ');
        }
        System.out.println(sb);
    }
}

answer/Homework02.java

java
/** Render CSV. */
public class Homework02 {
    public static void main(String[] args) {
        String csv = """
                name,age
                Jisoo,21
                Minsu,25
                """;
        System.out.print(csv);
    }
}

Try It Yourself

bash
cd 04_io/17_string/src
javac TextBlock.java
java TextBlock

Next Lecture

[18_Lambda](../../05_λͺ¨λ˜_μžλ°”/18_λžŒλ‹€/) β€” chapter 5 begins: lambdas and functional interfaces.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—