// sample-java21.java: newer Java syntax, for Java 21 (LTS) or later. // Free sample from 99helpers.com/file-types/java // // Useful for checking that an editor, linter, formatter or build server // understands current Java. On Java 17 it fails to compile, which is also // a quick way to find out which Java a tool really uses. // // Run it: java sample-java21.java // Or: javac sample-java21.java && java ModernJava import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.Future; final class ModernJava { // 1. A sealed interface (Java 17) names every class allowed to // implement it, so the compiler knows the full list. sealed interface Shape permits Circle, Square, Rectangle {} record Circle(double radius) implements Shape {} record Square(double side) implements Shape {} record Rectangle(double width, double height) implements Shape {} // 2. Pattern matching for switch with record patterns (both final in // Java 21). `Circle(double r)` takes the record apart; `when` adds a // condition. No `default` is needed: the interface is sealed, so the // compiler checks every case is covered. formatted() uses your // locale, so 3.14 prints as 3,14 in, say, Dutch or German. static String describe(Shape shape) { return switch (shape) { case Circle(double r) when r == 0 -> "a point"; case Circle(double r) -> "circle, area %.2f".formatted(Math.PI * r * r); case Square(double s) -> "square, area %.2f".formatted(s * s); case Rectangle(double w, double h) when w == h -> "a square in disguise"; case Rectangle(double w, double h) -> "rectangle, area %.2f".formatted(w * h); }; } public static void main(String[] args) throws Exception { List shapes = new ArrayList<>(List.of( new Circle(1), new Square(2), new Rectangle(2, 3), new Rectangle(4, 4))); shapes.add(new Circle(0)); // 3. Sequenced collections (Java 21): getFirst(), getLast() and // reversed() on lists, instead of get(0) and get(size() - 1). System.out.println("first: " + shapes.getFirst() + ", last: " + shapes.getLast()); for (Shape shape : shapes.reversed()) { System.out.println(describe(shape)); } // 4. Virtual threads (Java 21): very cheap threads, here one per // task. try-with-resources waits for all of them, then closes // the executor. try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { List> sums = new ArrayList<>(); for (int i = 1; i <= 1_000; i++) { long n = i; sums.add(executor.submit(() -> n * (n + 1) / 2)); } long total = 0; for (Future sum : sums) { total += sum.get(); } System.out.println("1,000 virtual threads, total " + total); } } }