JAVA-230 · Lesson 10 of 12 · 21 min
Text blocks, switch expressions and pattern matching
▶ Video coming soon A video version of this lesson is on the way.
Wednesday, November 24, was the evening Ingrid called "Java catching up". Between Java 14 and Java 21 the language gained a set of features that change how everyday code looks: text blocks for multi-line strings, switch as an expression, and pattern matching that tests a value's type and pulls it apart in one step. Hamza had already met some of them in passing, a text block in lesson 8 and a switch arrow in lesson 9's escaper. This session put them together, using the shop's report templates and the different kinds of events the booking system records.
Text blocks
A text block, final in Java 15, is a string literal that spans several lines, opened and closed with three double quotes. The opening quotes must be followed by a line break. Java removes the common indentation, so you can indent the block to match the surrounding code without the spaces ending up in the string; the position of the closing quotes counts as part of that indentation. Line endings are normalized to \n, quotes need no escaping, and two new escapes help: a backslash at the end of a line joins it to the next line, and \s keeps a trailing space that would otherwise be stripped. Text blocks suit JSON, SQL, HTML and report templates, and formatted fills in values the way String.format does.
public class Main {
public static void main(String[] args) {
String json = """
{
"code": "BELL",
"note": "Brass bell, rings twice"
}
""";
System.out.print(json);
String sql = """
SELECT code, quantity
FROM parts
WHERE quantity < reorder_at \
ORDER BY code""";
System.out.println(sql);
String header = """
%-12s %5s
%-12s %5d
""".formatted("Part", "Qty", "TUBE-700x25", 3);
System.out.print(header);
System.out.println("Lines in the JSON block: " + json.lines().count());
}
}{
"code": "BELL",
"note": "Brass bell, rings twice"
}
SELECT code, quantity
FROM parts
WHERE quantity < reorder_at ORDER BY code
Part Qty
TUBE-700x25 3
Lines in the JSON block: 4What this code does
The JSON block keeps its two-space inner indentation, because Java removes only the indentation all its lines share, and the double quotes around its names and values need no backslashes. The backslash at the end of the WHERE line joins it to the ORDER BY line, and because the SQL block's closing quotes sit on its last line, that string has no final line break. formatted fills the header template like String.format, and the JSON text has four lines.
Text blocks are ordinary String values once compiled, so every String method works on them, and stripIndent, translateEscapes and formatted were added to String in the same release for code that builds such text at run time.
Switch expressions
The old switch statement was easy to get wrong: forget a break and execution falls through into the next case. Java 14 made switch usable as an expression that produces a value, with arrow labels case X -> that never fall through, several labels per case separated by commas, and yield to return a value from a block. When a switch expression covers an enum or a sealed type, the compiler checks that every value is handled, so adding a constant later turns forgotten cases into compile errors instead of silent bugs.
import java.util.*;
public class Main {
enum Kind { FLAT, BRAKES, GEARS, WHEEL_TRUE, TUNE_UP }
static int standardMinutes(Kind k) {
return switch (k) {
case FLAT -> 20;
case BRAKES, GEARS -> 45;
case WHEEL_TRUE -> 40;
case TUNE_UP -> {
int inspect = 15, adjust = 50;
yield inspect + adjust;
}
};
}
static String oldStyle(Kind k) {
String label;
switch (k) {
case FLAT:
label = "quick";
case BRAKES:
label = "safety";
break;
default:
label = "standard";
}
return label;
}
public static void main(String[] args) {
for (Kind k : Kind.values()) System.out.println(k + ": " + standardMinutes(k) + " min");
System.out.println("Old switch labels FLAT as: " + oldStyle(Kind.FLAT));
}
}FLAT: 20 min BRAKES: 45 min GEARS: 45 min WHEEL_TRUE: 40 min TUNE_UP: 65 min Old switch labels FLAT as: safety
What this code does
standardMinutes is one switch expression that returns a value for every Kind, using one case for both BRAKES and GEARS and a yield inside a block for the tune-up. It has no default, and the compiler accepts that because every constant is covered. The old-style switch forgets a break after FLAT, so execution falls into the BRAKES case and labels a flat repair as safety, the classic fall-through bug the arrow form cannot have.
Pattern matching for instanceof
Before Java 16, checking a type and then using the value as that type took a test and a cast: if (e instanceof Rental) { Rental r = (Rental) e; ... }. A type pattern does both: if (e instanceof Rental r) tests the type and, only when the test succeeds, declares r already cast. The pattern variable is in scope wherever the compiler can prove the test passed, including the rest of a condition joined with &&, and after an early return in the negative case.
import java.util.*;
public class Main {
record Rental(String bike, int days) { }
record Repair(int ticket, int minutes) { }
record Sale(String code, long cents) { }
static String describe(Object event) {
if (event instanceof Rental r && r.days() >= 7) {
return "long rental of " + r.bike() + " (" + r.days() + " days)";
}
if (event instanceof Rental r) return "rental of " + r.bike();
if (!(event instanceof Repair rep)) return "other event: " + event;
return "repair " + rep.ticket() + ", " + rep.minutes() + " min";
}
public static void main(String[] args) {
List<Object> events = List.of(new Rental("CARGO-1", 9), new Rental("CITY-2", 2),
new Repair(531, 20), new Sale("BELL", 650));
events.forEach(e -> System.out.println(describe(e)));
}
}long rental of CARGO-1 (9 days) rental of CITY-2 repair 531, 20 min other event: Sale[code=BELL, cents=650]
What this code does
Each instanceof both tests the type and declares a variable of that type, so no casts are needed. In the first test the pattern variable r can be used after && because that part only runs when the match succeeded. The negated test returns early for anything that is not a Repair, so rep is in scope for the rest of the method.
Pattern matching in switch, and record patterns
Java 21 brought patterns to switch and added record patterns, which match a record and take its components apart in one step. A case Rental(String bike, int days) -> label matches any Rental and binds its two components to new variables; var can stand in for the types. A guard, written when followed by a condition, adds a test to a case. Cases are checked in order, so a more specific guarded case must come before a general one, and the compiler reports a case that can never be reached. A switch over patterns can also handle case null, which an old switch could not; without it, a null value throws NullPointerException as before.
import java.util.*;
public class Main {
record Rental(String bike, int days) { }
record Repair(int ticket, int minutes) { }
record Sale(String code, long cents) { }
static String line(Object event) {
return switch (event) {
case Rental(String bike, int days) when days >= 7 -> "LONG " + bike + " for " + days + " days";
case Rental(var bike, var days) -> "RENTAL " + bike + " for " + days + " days";
case Repair(int ticket, int minutes) -> "REPAIR #" + ticket + ", " + minutes + " min";
case Sale(String code, long cents) when cents >= 2000 -> "SALE " + code + " (large) " + cents + " cents";
case Sale s -> "SALE " + s.code() + " " + s.cents() + " cents";
case null -> "MISSING event";
default -> "UNKNOWN " + event;
};
}
static long withTax(Object event) {
return switch (event) {
case Sale(var code, var cents) -> Math.round(cents * 1.13);
default -> 0;
};
}
public static void main(String[] args) {
List<Object> events = new ArrayList<>(List.of(new Rental("CARGO-1", 9), new Rental("CITY-2", 2),
new Repair(531, 20), new Sale("CHAIN-11", 2499), new Sale("BELL", 650), "a note"));
events.add(null);
events.forEach(e -> System.out.println(line(e)));
System.out.println("Chain with HST: " + withTax(new Sale("CHAIN-11", 2499)) + " cents");
}
}LONG CARGO-1 for 9 days RENTAL CITY-2 for 2 days REPAIR #531, 20 min SALE CHAIN-11 (large) 2499 cents SALE BELL 650 cents UNKNOWN a note MISSING event Chain with HST: 2824 cents
What this code does
Each case either takes a record apart with a record pattern or binds the whole record to a variable, as case Sale s does. The guarded cases come first, so a nine-day rental and a 2,499-cent sale take the special labels while the others fall to the general cases, and case null handles the missing event that an old switch would have crashed on. The default case catches the plain string, because Object has subtypes that no case lists.
Because the parameter is Object, the switch needs a default; there is no way to list every possible class. Lesson 11 removes that need with sealed types, which tell the compiler the complete list of subtypes, so a switch over them can be checked for completeness just like a switch over an enum.
public class Main {
record Sale(String code, long cents) { }
static String size(Object o) {
return switch (o) {
case Sale s -> "sale";
case Sale(var code, var cents) when cents > 2000 -> "large sale";
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(size(new Sale("BELL", 650)));
}
}What this code does
The first case matches every Sale, so the guarded case after it can never be reached, and the compiler rejects the switch instead of silently ignoring the second case. The error message says that this case label is dominated by a preceding case label. Putting the guarded case first, as the earlier example does, fixes it.
$ javac Main.java
Main.java:7: error: this case label is dominated by a preceding case label
case Sale(var code, var cents) when cents > 2000 -> "large sale";
^
1 errorChoosing the newer forms
| Older form | Newer form | Since |
|---|---|---|
| String concatenation with \n | Text block | Java 15 |
| switch statement with break | switch expression with -> | Java 14 |
| instanceof then cast | instanceof with a type pattern | Java 16 |
| if/else chains on types | switch with type and record patterns | Java 21 |
| Accessor calls after a type test | Record patterns that bind components | Java 21 |
| default case on a closed set of types | Exhaustive switch over a sealed hierarchy | Java 21 (lesson 11) |
None of the old forms is gone, and plenty of existing code uses them, so you will read both. In new code, prefer the newer forms when they make intent clearer: a switch expression for choosing a value, patterns for code that branches on the kind of data, text blocks for any string longer than a line. Java 21 is the release where all of these are final; later releases add more, such as unnamed variables written _ in Java 22, which lesson 11 shows.
import java.util.*;
public class Main {
record Line(String code, int quantity, long priceCents) { }
static String receipt(String shop, List<Line> lines) {
StringBuilder rows = new StringBuilder();
long total = 0;
for (Line l : lines) {
long amount = l.quantity() * l.priceCents();
total += amount;
rows.append("%-12s %3d %8.2f%n".formatted(l.code(), l.quantity(), amount / 100.0));
}
return """
%s
------------------------------
%s------------------------------
Total %24.2f
""".formatted(shop, rows, total / 100.0);
}
public static void main(String[] args) {
System.out.print(receipt("Second Gear Cycles", List.of(
new Line("TUBE-700x25", 2, 899), new Line("BELL", 1, 650), new Line("CHAIN-11", 1, 2499))));
}
}Second Gear Cycles ------------------------------ TUBE-700x25 2 17.98 BELL 1 6.50 CHAIN-11 1 24.99 ------------------------------ Total 49.47
What this code does
The receipt layout lives in one text block, so the shape of the output is visible in the source, and formatted fills in the shop name, the rows and the total. Each row is built with its own small format string, padding the code to 12 characters and the amount to 8 with two decimals. The three lines total 4,947 cents, printed as 49.47.
By the end of the evening Hamza had replaced the booking system's twenty-line chain of instanceof checks with a single switch over record patterns, and the compiler had found one event type the old chain silently ignored.
Try it yourself
A switch expression for labels
Rewrite label as a single switch expression with arrow cases: CITY and CARGO give rental, TANDEM gives rental (two riders), and DEMO gives not for rent.
The program should print the four lines CITY: rental, CARGO: rental, TANDEM: rental (two riders) and DEMO: not for rent.
public class Main {
enum Type { CITY, CARGO, TANDEM, DEMO }
static String label(Type t) {
String s = "?";
switch (t) {
case CITY: s = "rental";
case CARGO: s = "rental"; break;
case TANDEM: s = "rental (two riders)";
case DEMO: s = "not for rent";
}
return s;
}
public static void main(String[] args) {
for (Type t : Type.values()) System.out.println(t + ": " + label(t));
}
}Try it yourself
Record patterns for events
Complete minutes with a switch over record patterns: a Repair(int ticket, int minutes) gives its minutes, a Fitting(String part, int count) gives 10 minutes per part, and anything else gives 0.
The program should print Shop time: 95 minutes.
import java.util.*;
public class Main {
record Repair(int ticket, int minutes) { }
record Fitting(String part, int count) { }
record Sale(String code, long cents) { }
static int minutes(Object event) {
return 0;
}
public static void main(String[] args) {
List<Object> day = List.of(new Repair(531, 45), new Fitting("BELL", 2), new Sale("TUBE-700x25", 899), new Repair(532, 30));
int total = 0;
for (Object e : day) total += minutes(e);
System.out.println("Shop time: " + total + " minutes");
}
}Common mistakes
MistakeConcatenating long strings with + and \n.
InsteadUse a text block, with formatted for values.
MistakeForgetting break in an old switch.
InsteadUse arrow cases, which never fall through.
MistakeWriting instanceof followed by a cast.
InsteadUse a type pattern: if (e instanceof Rental r).
MistakePutting a general case before a guarded one.
InsteadOrder cases from most specific to most general; the compiler rejects dominated cases.
MistakeAdding a default to a switch over an enum just in case.
InsteadLeave it out so the compiler reports a new constant that is not handled.
Summary and key terms
- Text blocks, final in Java 15, are multi-line string literals in triple quotes; Java removes their common indentation, normalizes line endings and needs no escaped quotes, and formatted fills in values.
- Switch expressions, final in Java 14, produce a value, use arrow cases that never fall through, allow several labels per case and use yield in blocks; over an enum they must cover every constant.
- Type patterns, final in Java 16, combine instanceof with a cast.
- Java 21 added patterns in switch and record patterns that take records apart, with when guards, case null and checks for exhaustiveness and dominated cases.
- Cases are tried in order, so specific cases come first.
- A switch over Object needs a default; a switch over a sealed type, covered next lesson, does not.
- Text block
- A multi-line string literal written between three double quotes.
- Incidental indentation
- The common leading spaces of a text block, which Java removes.
- Switch expression
- A switch that produces a value, written with arrow cases.
- yield
- The statement that gives the value of a switch expression from inside a block.
- Fall-through
- In an old switch, running on into the next case when a break is missing.
- Type pattern
- A pattern such as Rental r that tests a type and declares a variable of that type.
- Record pattern
- A pattern such as Rental(var bike, var days) that matches a record and binds its components.
- Guard
- A when condition that adds a test to a case in a pattern switch.
- Exhaustive switch
- A switch whose cases cover every possible value, checked by the compiler.
- Dominated case
- A case that can never match because an earlier case matches everything it would.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What does Java remove from a text block?
Show answer
The indentation that all its lines share.
Why can an arrow-case switch not fall through?
Show answer
Each arrow case runs only its own expression or block.
What does if (e instanceof Rental r) do?
Show answer
Tests whether e is a Rental and, if so, declares r as that Rental.
What does case Rental(var bike, var days) when days >= 7 match?
Show answer
Rentals of seven days or more, binding the bike and days.
Why does a switch over Object need a default?
Show answer
The compiler cannot know every possible subtype of Object.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.