Java Text Blocks & Modern Java
Java has changed a lot since Java 8. A new version ships every six months, and many recent features make everyday code shorter and safer. This chapter tours the most useful ones you'll meet in modern codebases.
| Feature | Since | In one sentence |
|---|---|---|
var |
10 | local type inference |
| switch expressions | 14 | switch that returns a value, with -> arms |
| text blocks | 15 | multi-line string literals with """ |
| records | 16 | concise immutable data classes |
pattern matching for instanceof |
16 | test and cast in one step |
| sealed classes | 17 | restrict which classes may extend a type |
pattern matching for switch, record patterns |
21 | switch on types and deconstruct records |
| sequenced collections | 21 | getFirst(), getLast(), reversed() on lists and more |
unnamed variables _ |
22 | ignore values you don't need |
| module imports, compact source files | 25 | import module ..., simpler single-file programs |
Text blocks
A text block starts with """ followed by a line break and ends with """. It can span many lines without \n and +, and quotes don't need escaping. The common indentation is removed automatically, based on the least-indented line (including the closing """):
class Main {
public static void main(String[] args) {
String json = """
{
"name": "ExcelTAD",
"language": "Java",
"tags": ["tutorial", "playground"]
}
""";
System.out.print(json);
String old = "{\n \"name\": \"ExcelTAD\"\n}\n"; // the same thing, the old way
System.out.print(old);
}
}{
"name": "ExcelTAD",
"language": "Java",
"tags": ["tutorial", "playground"]
}
{
"name": "ExcelTAD"
}
Text blocks are perfect for JSON, SQL, HTML and test data. Combine them with formatted() to insert values:
class Main {
public static void main(String[] args) {
String sql = """
SELECT id, name
FROM customers
WHERE country = '%s'
AND orders > %d
""".formatted("NO", 5);
System.out.print(sql);
String oneLine = """
This long sentence is written over \
two source lines but stays one line.""";
System.out.println(oneLine);
}
}SELECT id, name
FROM customers
WHERE country = 'NO'
AND orders > 5
This long sentence is written over two source lines but stays one line.
A backslash at the end of a line joins it with the next one, and \s keeps a trailing space that would otherwise be stripped.
Pattern matching for switch
Modern switch can test the type of a value, deconstruct records, and add conditions with when. Combined with a sealed interface, the compiler checks that every case is covered:
import java.util.List;
sealed interface Payment permits Card, Transfer, Voucher { }
record Card(String last4, double amount) implements Payment { }
record Transfer(String iban, double amount) implements Payment { }
record Voucher(String code) implements Payment { }
class Main {
static String describe(Payment p) {
return switch (p) {
case Card(String last4, double amt) when amt > 500 -> "Large card payment " + amt + " (needs review)";
case Card(String last4, double amt) -> "Card ****" + last4 + ": " + amt;
case Transfer t -> "Transfer from " + t.iban().substring(0, 4) + "...: " + t.amount();
case Voucher(var code) -> "Voucher " + code;
};
}
static String kind(Object o) {
return switch (o) {
case null -> "null!";
case Integer i when i < 0 -> "negative int";
case Integer i -> "int " + i;
case String s -> "string of length " + s.length();
default -> "something else: " + o.getClass().getSimpleName();
};
}
public static void main(String[] args) {
List<Payment> payments = List.of(
new Card("4242", 89.99), new Card("1111", 1200),
new Transfer("NO9386011117947", 250), new Voucher("WELCOME10"));
payments.forEach(p -> System.out.println(describe(p)));
for (Object o : new Object[] {7, -3, "hey", 2.5, null}) {
System.out.println(kind(o));
}
}
}Card ****4242: 89.99
Large card payment 1200.0 (needs review)
Transfer from NO93...: 250.0
Voucher WELCOME10
int 7
negative int
string of length 3
something else: Double
null!
Sequenced collections and unnamed variables
Java 21 gave lists, deques, LinkedHashSet and LinkedHashMap a common interface with first/last access. Java 22 added _ for variables you must declare but never use:
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SequencedMap;
class Main {
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("first", "middle", "last"));
System.out.println(queue.getFirst() + " / " + queue.getLast());
System.out.println(queue.reversed());
queue.addFirst("new-first");
System.out.println(queue);
SequencedMap<String, Integer> ranking = new LinkedHashMap<>();
ranking.put("gold", 1);
ranking.put("silver", 2);
ranking.put("bronze", 3);
System.out.println(ranking.firstEntry() + " ... " + ranking.lastEntry());
int count = 0;
for (String _ : queue) { // we only count, the element is unused
count++;
}
System.out.println("Count: " + count);
try {
Integer.parseInt("oops");
} catch (NumberFormatException _) {
System.out.println("Not a number");
}
}
}first / last
[last, middle, first]
[new-first, first, middle, last]
gold=1 ... bronze=3
Count: 4
Not a number
Other handy modern APIs
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
// Immutable collection factories (Java 9+)
List<String> langs = List.of("Java", "Kotlin", "Scala");
Map<String, Integer> years = Map.of("Java", 1995);
// String helpers (Java 11+)
System.out.println(" padded ".strip() + "|" + " ".isBlank() + "|" + "ab".repeat(3));
System.out.println("line1\nline2\nline3".lines().count());
// Stream.toList (Java 16+), Collectors.teeing (Java 12+)
var lengths = langs.stream().map(String::length).toList();
System.out.println(lengths);
String summary = langs.stream().collect(Collectors.teeing(
Collectors.counting(),
Collectors.joining("/"),
(n, names) -> n + " languages: " + names));
System.out.println(summary);
System.out.println(years.get("Java"));
// Helpful NullPointerException messages (Java 14+)
try {
String s = null;
s.length();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}padded|true|ababab
3
[4, 6, 5]
3 languages: Java/Kotlin/Scala
1995
Cannot invoke "String.length()" because "<local5>" is null
The last line shows Java's detailed NPE messages, which name the exact expression that was null. (With debug information enabled, the variable name s appears instead of <local5>.)
Simpler programs for beginners
Java 25 finalised compact source files and instance main methods. A small program no longer needs a class declaration or public static, and the new IO class offers simple console methods:
void main() {
IO.println("Hello from Java 25!");
}Save it as Hello.java and run it with java Hello.java. Under the hood Java still wraps it in a class; it simply hides the ceremony while you're learning.
Tip: Check which Java version your project targets before using new features. Long-term-support (LTS) releases — 17, 21 and 25 — are what most companies run in production.
Test yourself
How does a text block begin?
- With ''' on the same line as the text
- With """ followed by a line break
- With a backtick
- With @"
What does when do in case Integer i when i > 0 ->?
- Loops while i > 0
- Adds a guard condition to the pattern
- Casts i to boolean
- It is a syntax error
Why can a switch over a sealed interface omit default?
- Sealed types can't be switched on
- The compiler knows all permitted subtypes and can check exhaustiveness
- default is always optional
- Because records are final