17. Strings and Text Blocks
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
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.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append("#").append(i);
String result = sb.toString(); // #0#1#2#3#43) Text blocks (JDK 15+)
String json = """
{
"name": "Jisoo",
"age": 21
}
""";Indentation is auto-aligned to the closing `"""`.
4) `String.format` and `formatted`
String s1 = String.format("name=%s, age=%d", "Jisoo", 21);
String s2 = "name=%s, age=%d".formatted("Jisoo", 21); // JDK 15+5) `String.join`
String csv = String.join(",", "a", "b", "c"); // a,b,cExamples
Example 1 β `Common.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**
length=12
upper=HELLO, JAVA!
contains Java? true
replace=Hello, World!Example 2 β `StringBuilderDemo.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**
#0#1#2#3#4
length=10
reversed=4#3#2#1#0#Example 3 β `TextBlock.java`
public class TextBlock {
public static void main(String[] args) {
String json = """
{
"name": "Jisoo",
"age": 21
}
""";
System.out.println(json);
}
}**Output**
{
"name": "Jisoo",
"age": 21
}
Example 4 β `FormatDemo.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**
name=Jisoo, age=21, score=92.50
Hello, World!Common Mistakes
- Concatenating in tight loops with `+` instead of `StringBuilder`
- Comparing strings with `==` instead of `.equals()`
- Forgetting that `split` takes a regex (so `split(".")` matches everything)
- Indentation mistakes in a text block leaking leading spaces
- 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
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
name,age
Jisoo,21
Minsu,25## Solutions After trying it yourself, compare with [`answer/`](./answer/).
Solution code (homework/answer/)
answer/Homework01.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
/** 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
cd 04_io/17_string/src
javac TextBlock.java
java TextBlockNext Lecture
[18_Lambda](../../05_λͺ¨λ_μλ°/18_λλ€/) β chapter 5 begins: lambdas and functional interfaces.
All lecture materials and example code are openly available on GitHub.
View on GitHub β