Java 21 Features
- Switch Expressions
- Pattern Matching for instanceof
- Records
- Text Blocks
- Sealed Classes
- Local Interfaces
Switch Expressions
Java 21 introduces a simplified syntax for switch statements, allowing them to be used as expressions. This enables more concise and readable code.
Example Code:
int day = 3;
String dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
System.out.println("Day type: " + dayType);
Pattern Matching for instanceof
Java 21 introduces pattern matching for the instanceof operator, allowing for more concise and readable code when working with object types.
Example Code:
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println("Length of string: " + s.length());
} else {
System.out.println("Not a string");
}
Records
Java 21 introduces record classes, which are a concise way to declare classes that are essentially data carriers, automatically generating constructors, accessors, and equals()
and hashCode()
methods.
Example Code:
public record Person(String name, int age) {
// Record class automatically defines:
// - Constructor
// - Accessor methods
// - equals() and hashCode() methods
}
Text Blocks
Java 21 introduces text blocks, which allow for multiline string literals without the need for escape characters. This improves readability and maintainability of code.
Example Code:
String html = """
<html>
<body>
<p>Hello, world!</p>
</body>
</html>
""";
System.out.println(html);
Sealed Classes
Java 21 introduces sealed classes, which restrict the subclasses that can extend or implement them, providing more control over class hierarchies.
Example Code:
public sealed interface Shape permits Circle, Rectangle, Triangle {
// Interface definition
}
Local Interfaces
Java 21 allows the declaration of interfaces within methods, known as local interfaces. This can be useful for encapsulating functionality within a method.
Example Code:
public void process() {
interface Callback {
void onSuccess();
void onFailure();
}
// Local interface usage
}
No comments:
Post a Comment