Java: Modern Java – code examples
Contents
sealed interface + switch
Modern Java#sealed#pattern#switch#record
Use case: Model closed sets of cases, e.g. payment methods, shapes or event types.
public class Main {
sealed interface Form permits Kreis, Rechteck {}
record Kreis(double radius) implements Form {}
record Rechteck(double b, double h) implements Form {}
static double flaeche(Form f) {
return switch (f) {
case Kreis k -> Math.PI * k.radius() * k.radius();
case Rechteck r -> r.b() * r.h();
};
}
public static void main(String[] args) {
System.out.println(Math.round(flaeche(new Kreis(2))));
System.out.println(flaeche(new Rechteck(3, 4)));
}
}The compiler knows there are only Kreis and Rechteck – a default is unnecessary. If you add a shape, it reports the missing case. Output: 13 and 12.0.
Record patterns: expression tree
Modern Java#record#pattern#recursion
Use case: Evaluate tree structures (expressions, syntax trees, rules) recursively.
public class Main {
sealed interface Ausdruck permits Zahl, Add, Mul {}
record Zahl(int wert) implements Ausdruck {}
record Add(Ausdruck l, Ausdruck r) implements Ausdruck {}
record Mul(Ausdruck l, Ausdruck r) implements Ausdruck {}
static int auswerten(Ausdruck e) {
return switch (e) {
case Zahl z -> z.wert();
case Add(Ausdruck l, Ausdruck r) -> auswerten(l) + auswerten(r);
case Mul(Ausdruck l, Ausdruck r) -> auswerten(l) * auswerten(r);
};
}
public static void main(String[] args) {
System.out.println(auswerten(new Add(new Zahl(2), new Mul(new Zahl(3), new Zahl(4)))));
}
}Record patterns (Java 21) destructure records directly in the case. 2 + 3 * 4 gives 14.
instanceof with pattern
Modern Java#instanceof#pattern#cast
Use case: Safely check objects of unknown type and keep using them without a cast.
public class Main {
static String beschreibe(Object o) {
if (o instanceof String s && !s.isEmpty()) {
return "Text with " + s.length() + " characters";
}
if (o instanceof Integer i) {
return "Number " + (i + 1);
}
return "unknown";
}
public static void main(String[] args) {
System.out.println(beschreibe("Hello"));
System.out.println(beschreibe(41));
System.out.println(beschreibe(3.5));
}
}The variable s or i is typed directly on success – no cast needed. Output: Text with 5 characters, Number 42, unknown.
Sequenced collections (Java 21)
Modern Java#list#java21#sequenced
Use case: Conveniently read the first and last element of a list or reverse the list.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> l = new ArrayList<>(List.of("a", "b", "c"));
System.out.println(l.getFirst() + " " + l.getLast());
System.out.println(l.reversed());
l.addFirst("z");
System.out.println(l);
}
}Since Java 21 there are getFirst, getLast, addFirst, reversed for lists, deques and LinkedHashSet/-Map. Output: a c, [c, b, a], [z, a, b, c].