Top 5 Features of JDK 17 with Complete Examples
Java 17, being a Long-Term Support (LTS) release, brings several new powerful features aimed at improving developer productivity, code clarity, and application performance. In this blog, we will explore the top 5 most exciting features of JDK 17, complete with runnable examples and in-depth explanations.
✅ Feature 1: Sealed Classes
Sealed classes provide a way to restrict which classes can extend or implement a particular class or interface. It improves domain modeling and helps maintain strong control over inheritance, making the code more predictable and secure.
Complete Example:
// File: Animal.java
public sealed class Animal permits Dog, Cat {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
// File: Dog.java
public final class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark!");
}
}
// File: Cat.java
public final class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
// File: Main.java
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // Output: Bark!
Animal cat = new Cat();
cat.makeSound(); // Output: Meow!
}
}
🧠Detailed Explanation:
- sealed classes/interfaces explicitly define the allowed subclasses using the permits clause.
- Subclasses must be declared as
final
,sealed
, ornon-sealed
. - This improves API design, security, and makes your code easier to reason about in complex hierarchies.
✅ Feature 2: Pattern Matching for instanceof
Pattern matching simplifies type checks and casts. It reduces boilerplate and improves code readability significantly when using the instanceof
operator.
Complete Example:
public class PatternMatchDemo {
public static void main(String[] args) {
Object obj = "Java 17";
if (obj instanceof String str) {
System.out.println("String length: " + str.length());
}
}
}
🧠Detailed Explanation:
- Traditionally, after using
instanceof
, a manual cast was required. - Pattern matching allows declaring a new variable (e.g.,
String str
) inside theif
condition itself. - This approach results in fewer lines of code, minimizes casting errors, and increases code safety and clarity.
✅ Feature 3: Switch Expressions Enhancements
Switch expressions have been enhanced to allow more powerful and expressive switch constructs, with support for returning values and multiple labels per case.
Complete Example:
public class SwitchExpressionDemo {
public static void main(String[] args) {
String day = "MONDAY";
String result = switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY" -> "Weekday";
case "SATURDAY", "SUNDAY" -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
System.out.println("Day type: " + result);
}
}
🧠Detailed Explanation:
- New syntax with -> makes switch expressions concise and less error-prone.
- Multiple case labels (e.g., "MONDAY", "TUESDAY") grouped together naturally.
- Default case must be handled, ensuring the switch is exhaustive and predictable.
✅ Feature 4: Text Blocks
Text blocks allow you to declare multi-line strings easily using triple quotes """
. They automatically preserve formatting and eliminate the need for explicit newline characters.
Complete Example:
public class TextBlockDemo {
public static void main(String[] args) {
String html = """
Welcome to Java 17
""";
System.out.println(html);
}
}
🧠Detailed Explanation:
- No need to manually insert
\n
for new lines or escape quotes inside the string. - Improves readability, especially when embedding HTML, SQL, JSON, XML, etc.
- Leading whitespace can be automatically trimmed for a cleaner output.
✅ Feature 5: Record Classes
Records provide a compact syntax for declaring classes that are transparent holders for shallowly immutable data. They are perfect for creating DTOs, API models, and simple value objects.
Complete Example:
public record User(String name, int age) {}
public class RecordDemo {
public static void main(String[] args) {
User user = new User("Alice", 30);
System.out.println(user.name());
System.out.println(user.age());
System.out.println(user); // Outputs: User[name=Alice, age=30]
}
}
🧠Detailed Explanation:
- When you declare a record, Java automatically generates the constructor, getters,
equals()
,hashCode()
, andtoString()
. - Records are immutable by default, promoting functional programming principles.
- They reduce boilerplate significantly, keeping the code clean and maintainable.
📌 Conclusion
Java 17 is a powerhouse release that streamlines many of the common pain points developers face. Sealed classes help with better domain modeling, pattern matching reduces boilerplate, enhanced switch expressions and text blocks boost productivity, and records make your data objects cleaner and faster to implement.
Comments
Post a Comment