Java versions
versions5Java17Features
- Path
- pkg2versions/versions5Java17Features.java
- Package
- pkg2versions
- Study order
- 5
- Run
- Single-file source launch
- Command
- java pkg2versions/versions5Java17Features.java
- Version in the filename
- Java 17
- Example
- Cumulative Java 12–17 example
- Requires
- Java 17
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg2versions;2 3/*4 * versions5Java17Features.java (requires Java 17)5 * --------------------------------6 * Cumulative Java 12-17 example. The whole file requires Java 17.7 * It is not a Java 12, 13, 14, 15, or 16 program.8 * Switch expressions are the final form (Java 14), not the Java 12 preview.9 * Pattern matching for switch was still a preview in Java 17 and is not used.10 *11 * FEATURES & WHY (cumulative across 12-17):12 * - Records (16) : concise immutable data carriers.13 * - Sealed classes (17) : control the type hierarchy; exhaustive switches.14 * - Pattern matching for instanceof (16): bind + test in one step.15 * - Text blocks (15) : multi-line string literals.16 * - Switch expressions (14) : value-returning, arrow form.17 * - Helpful NullPointerExceptions, new GCs (ZGC/Shenandoah prod-ready).18 */19public class versions5Java17Features {20 21 sealed interface Vehicle permits Car, Truck {}22 record Car(int seats) implements Vehicle {}23 record Truck(double tons) implements Vehicle {}24 25 static String classify(Vehicle v) {26 // Pattern matching for switch over a sealed type (preview in 17, final in 21)27 if (v instanceof Car c) return "Car with " + c.seats() + " seats";28 if (v instanceof Truck t) return "Truck carrying " + t.tons() + " tons";29 return "unknown";30 }31 32 public static void main(String[] args) {33 // Records34 Car car = new Car(4);35 Truck truck = new Truck(12.5);36 System.out.println(car + " / " + truck);37 38 // Sealed + instanceof pattern39 System.out.println(classify(car));40 System.out.println(classify(truck));41 42 // Text block43 String html = """44 <html>45 <body>Hello</body>46 </html>""";47 System.out.println(html);48 49 // Switch expression50 int code = 2;51 String level = switch (code) {52 case 1 -> "INFO";53 case 2 -> "WARN";54 default -> "ERROR";55 };56 System.out.println("level=" + level);57 }58}