JVM / Java / Versions / Improvements
1. Records
Starting with Java 17.
No getter, constructor, equals, hashCode.
Immutable by default.
public class RecordExample {
public static void main(String[] args) {
Person p = new Person("John", 20);
System.out.println(p.name());
System.out.println(p.age());
System.out.println(p);
}
}
record Person(String name, int age) {}
2. Pattern Matching
Starting with Java 17.
No explicit cast (less boilerplate).
More readable.
public class PatternMatchingExample {
void main() {
Object obj = "Hello";
if (obj instanceof String) {
String str = (String) obj;
System.out.println(str.length());
}
Object obj2 = "Hello";
if (obj2 instanceof String str) {
System.out.println(str.length());
}
Object obj3 = new Person("Bob", 30);
if (obj3 instanceof Person(String name, int age)) {
System.out.println(name + " is " + age);
}
}
}
record Person(String name, int age) {}
3. Switch Improvements
Starting with Java 17.
No fallthrough bugs.
Works with types (Java 21).
package versions;
public class SwitchExample {
void main() {
switchJava8();
switchJava17();
switchJava21();
}
void switchJava8() {
int day =2;
String result;
switch (day) {
case 1:
result = "Mon";
break;
case 2:
result = "Tue";
break;
default:
result = "Other";
}
System.out.println(result);
}
void switchJava17() {
int day = 2;
String result = switch(day) {
case 1 -> "Mon";
case 2 -> "Tue";
default -> "Other";
};
System.out.println(result);
}
void switchJava21() {
Object obj = 10;
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown";
};
System.out.println(result);
}
}