Add java21-features module: runnable demos and captured output for the ankurm.com java21-features article

This commit is contained in:
2026-10-20 17:13:59 +00:00
parent 5a076c826f
commit c3cc57f482
33 changed files with 354 additions and 0 deletions
@@ -0,0 +1,20 @@
/** JEP 440 (final): deconstruct records in instanceof and switch, nested. */
public class RecordPatternsDemo {
record Point(int x, int y) {}
record Line(Point from, Point to) {}
record Box<T>(T content) {}
static String describe(Object o) {
if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2)))
return "line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ") length^2=" + ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
if (o instanceof Box<?>(String s)) return "box of String " + s;
if (o instanceof Box<?>(Integer i)) return "box of Integer " + i;
return "no match";
}
public static void main(String[] args) {
System.out.println(describe(new Line(new Point(0, 0), new Point(3, 4))));
System.out.println(describe(new Box<>("hi")));
System.out.println(describe(new Box<>(7)));
System.out.println(describe(new Box<>(2.5)));
}
}