Java 17 is a Long-Term Support (LTS) release that introduced several important language enhancements and JVM improvements. It became widely adopted in enterprise applications.
1. Sealed Classes
Sealed classes restrict which classes can extend or implement them.
public sealed class Shape
permits Circle, Rectangle {}
final class Circle extends Shape {}
final class Rectangle extends Shape {}
Sealed classes help control inheritance and improve code safety.
Interview Question: Why use sealed classes?
Answer: To restrict which classes can extend a class or interface.
Answer: To restrict which classes can extend a class or interface.
2. Records
Records provide a concise way to create immutable data classes.
record Person(String name, int age) {}
Person p = new Person("John", 30);
System.out.println(p.name());
Records automatically generate constructor, getters, equals, hashCode, and toString.
3. Pattern Matching for instanceof
Simplifies type checking and casting.
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
Eliminates the need for manual casting after instanceof checks.
4. Text Blocks
Text blocks allow writing multi-line strings easily.
String json = """
{
"name": "Java",
"version": 17
}
""";
System.out.println(json);
Useful for JSON, SQL queries, and HTML content.
5. Enhanced Pseudo-Random Number Generators
Java 17 introduced new interfaces for generating random numbers.
RandomGenerator generator = RandomGenerator.getDefault();
int number = generator.nextInt(100);
System.out.println(number);
Provides better control over random number generation.
6. Improved Switch Expressions
Switch expressions became more powerful and concise.
int day = 2;
String result = switch(day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Other";
};
System.out.println(result);
Switch expressions improve readability and reduce boilerplate code.
Quick Revision Summary
- Sealed Classes
- Records
- Pattern Matching for instanceof
- Text Blocks
- Enhanced Random Number Generators
- Improved Switch Expressions
0 comments