Add java17-features module: runnable demos and captured output for the ankurm.com java17-features article
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
/** JEP 403: strong encapsulation of JDK internals. Same code, different outcome on 11 and 17. */
|
||||
public class EncapsulationDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Field f = String.class.getDeclaredField("value");
|
||||
try {
|
||||
f.setAccessible(true);
|
||||
Object v = f.get("abc");
|
||||
System.out.println("read String.value: " + v.getClass().getSimpleName());
|
||||
} catch (RuntimeException e) {
|
||||
System.out.println(e.getClass().getName() + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Helpful NullPointerException messages (JEP 358): on by default since 15. */
|
||||
public class HelpfulNpeDemo {
|
||||
static class Address { String city; }
|
||||
static class User { Address address; }
|
||||
public static void main(String[] args) {
|
||||
User u = new User();
|
||||
try { System.out.println(u.address.city.length()); }
|
||||
catch (NullPointerException e) { System.out.println(e.getMessage()); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Pattern matching for instanceof (final in 16, JEP 394) and Stream.toList() (16). */
|
||||
public class PatternInstanceofDemo {
|
||||
static String describe(Object o) {
|
||||
if (o instanceof String s && s.length() > 3) return "long string " + s;
|
||||
if (o instanceof Integer i) return "int " + (i + 1);
|
||||
return "other " + o;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
System.out.println(describe("hello"));
|
||||
System.out.println(describe("hi"));
|
||||
System.out.println(describe(41));
|
||||
var list = java.util.stream.Stream.of(3, 1, 2).sorted().toList();
|
||||
System.out.println("Stream.toList : " + list);
|
||||
try { list.add(4); } catch (UnsupportedOperationException e) { System.out.println("toList() result is unmodifiable"); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
|
||||
/** JEP 356: RandomGenerator interface and named algorithms. Seeded, so the output is stable. */
|
||||
public class RandomDemo {
|
||||
public static void main(String[] args) {
|
||||
RandomGenerator g = RandomGeneratorFactory.of("L64X128MixRandom").create(42L);
|
||||
System.out.println("L64X128MixRandom nextInt(100) x3: " + g.nextInt(100) + " " + g.nextInt(100) + " " + g.nextInt(100));
|
||||
System.out.println("ThreadLocalRandom implements RandomGenerator: " + (java.util.concurrent.ThreadLocalRandom.current() instanceof RandomGenerator));
|
||||
System.out.println("algorithms >= 10: " + (RandomGeneratorFactory.all().count() >= 10));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Records (final in 16, JEP 395): what the compiler generates, compact constructors, and the shallow-immutability caveat. */
|
||||
public class RecordsDemo {
|
||||
record Point(int x, int y) {
|
||||
Point { if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate: " + x + "," + y); }
|
||||
double distance() { return Math.sqrt(x * x + y * y); }
|
||||
}
|
||||
record Team(String name, java.util.List<String> members) {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Point p = new Point(3, 4);
|
||||
System.out.println("toString : " + p);
|
||||
System.out.println("equals : " + p.equals(new Point(3, 4)) + " hashCode equal: " + (p.hashCode() == new Point(3, 4).hashCode()));
|
||||
System.out.println("accessor : p.x() = " + p.x() + ", distance = " + p.distance());
|
||||
try { new Point(-1, 2); } catch (IllegalArgumentException e) { System.out.println("compact ctor : " + e.getMessage()); }
|
||||
|
||||
java.util.List<String> list = new java.util.ArrayList<>(java.util.List.of("a"));
|
||||
Team t = new Team("core", list);
|
||||
list.add("b");
|
||||
System.out.println("shallow : " + t + " <- the record's list changed after construction");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Sealed classes (final in 17, JEP 409): the compiler knows every permitted subtype. */
|
||||
public class SealedDemo {
|
||||
sealed interface Shape permits Circle, Square, Rect {}
|
||||
record Circle(double r) implements Shape {}
|
||||
record Square(double side) implements Shape {}
|
||||
record Rect(double w, double h) implements Shape {}
|
||||
|
||||
// On 17 the switch must still be an if-chain: pattern matching for switch is only a preview here (JEP 406)
|
||||
static double area(Shape s) {
|
||||
if (s instanceof Circle c) return Math.PI * c.r() * c.r();
|
||||
if (s instanceof Square q) return q.side() * q.side();
|
||||
if (s instanceof Rect r) return r.w() * r.h();
|
||||
throw new AssertionError("unreachable for a sealed Shape");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
for (Shape s : new Shape[] { new Circle(1), new Square(2), new Rect(2, 3) })
|
||||
System.out.printf("%-26s area = %.3f%n", s, area(s));
|
||||
System.out.println("permitted : " + java.util.Arrays.stream(Shape.class.getPermittedSubclasses()).map(Class::getSimpleName).toList());
|
||||
System.out.println("isSealed : " + Shape.class.isSealed());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Switch expressions (final in 14, JEP 361): arrow form, no fall-through, yield, and exhaustiveness on enums. */
|
||||
public class SwitchExprDemo {
|
||||
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
|
||||
public static void main(String[] args) {
|
||||
for (Day d : new Day[] { Day.MON, Day.SAT, Day.WED }) {
|
||||
int len = switch (d) {
|
||||
case SAT, SUN -> 0;
|
||||
case MON, TUE, WED, THU, FRI -> {
|
||||
int hours = d == Day.MON ? 9 : 8;
|
||||
yield hours;
|
||||
}
|
||||
};
|
||||
System.out.println(d + " -> " + len + " working hours");
|
||||
}
|
||||
// old style: forgetting break falls through
|
||||
int n = 1; StringBuilder sb = new StringBuilder();
|
||||
switch (n) { case 1: sb.append("one "); case 2: sb.append("two "); break; case 3: sb.append("three"); }
|
||||
System.out.println("old fall-through: " + sb.toString().trim());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/** Text blocks (final in 15, JEP 378): indentation stripping, trailing-space and escape rules. */
|
||||
public class TextBlocksDemo {
|
||||
public static void main(String[] args) {
|
||||
String json = """
|
||||
{
|
||||
"name": "Ankur",
|
||||
"city": "Mumbai"
|
||||
}
|
||||
""";
|
||||
System.out.print(json);
|
||||
System.out.println("lines : " + json.lines().count());
|
||||
String oneLine = """
|
||||
joined \
|
||||
on one line""";
|
||||
System.out.println("backslash-newline: " + oneLine);
|
||||
System.out.println("formatted : " + """
|
||||
Hello, %s!""".formatted("reader"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user