Java has evolved significantly over the years, introducing powerful new features that enhance readability, performance, and developer productivity. In this article, we explore key language improvements from Java 9 to Java 22, including the Java Platform Module System, local variable type inference, switch expressions, text blocks, record classes, sealed types, and advanced pattern matching. Through a practical Java program, we demonstrate how these features work together to simplify coding and improve maintainability. Whether you're a seasoned developer or just starting with modern Java, this guide will help you stay up to date with the latest advancements.
import java.util.*;
// Java 16: Record Classes (JEP 395)
record Person(String name, int age) {}
// Java 17: Sealed Classes (JEP 409)
sealed interface Animal permits Dog, Cat {}
record Dog(String name) implements Animal {}
record Cat(String name) implements Animal {}
public class JavaFeaturesDemo {
public static void main(String[] args) {
// Java 10: Local Variable Type Inference (JEP 286)
var message = "Hello, Java!";
System.out.println(message);
// Java 11: Local-Variable Syntax for Lambda Parameters (JEP 323)
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach((var name) -> System.out.println("Hello, " + name));
// Java 14: Switch Expressions and Statements (JEP 361)
int day = 3;
var dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Unknown";
};
System.out.println("Day type: " + dayType);
// Java 15: Text Blocks (JEP 378)
String json = """
{
"name": "John",
"age": 30
}
""";
System.out.println("JSON Data: " + json);
// Java 16: Pattern Matching with instanceof (JEP 394)
Object obj = "Pattern Matching Example";
if (obj instanceof String str) {
System.out.println("String length: " + str.length());
}
// Java 21: Record Patterns (JEP 440) and Pattern Matching with switch (JEP 441)
Person person = new Person("John", 25);
switch (person) {
case Person(var name, var age) -> System.out.println("Person: " + name + ", Age: " + age);
}
// Java 22: Unnamed Variables and Patterns (JEP 456)
Person unnamedPerson = new Person("Jane", 30);
if (unnamedPerson instanceof Person(String _, int age)) {
System.out.println("Age: " + age);
}
}
}
One way to improve your understanding of the latest Java changes is by taking Oracle Java Certifications.
Top comments (0)