Java 14 Features
1. πΉΒ Switch Expressions (Standard Feature β JEP 361)
After being in preview in Java 12 and 13, switch expressions became official in Java 14.
Example:
String day = "MONDAY";
int result = switch (day) {
case "MONDAY", "FRIDAY" -> 6;
case "TUESDAY" -> 2;
default -> 0;
};
System.out.println(result); // Output: 6
β Enables switch to return values and prevents fall-through errors.
2. πΉ Text Blocks (2nd Preview β JEP 368)
Multi-line string literals continue to improve with feedback from Java 13.
Example:
String json = """
{
"name": "Java",
"version": 14
}
""";
System.out.println(json);
Use
--enable-preview
flag to run this in Java 14.
3. πΉ Records (Preview β JEP 359)
A record is a new kind of class in Java meant to model immutable data. It automatically generates equals()
, hashCode()
, toString()
, and a constructor.
Example:
record Person(String name, int age) {}
public class Main {
public static void main(String[] args) {
Person p = new Person("Alice", 30);
System.out.println(p.name()); // Alice
System.out.println(p); // Person[name=Alice, age=30]
}
}
β Great for DTOs or simple data holders.
4. πΉ Pattern Matching for instanceof
(Preview β JEP 305)
Reduces boilerplate code for instanceof
type checking and casting.
Before Java 14:
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
Java 14 (Preview):
if (obj instanceof String s) {
System.out.println(s.length());
}
β Cleaner and less error-prone.
5. πΉ Helpful NullPointerExceptions (JEP 358)
The JVM now provides detailed messages showing which variable was null in a chain.
Example Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Address.getCity()" because "user.getAddress()" is null
β Major improvement for debugging nulls!
6. πΉ Foreign-Memory Access API (Incubator β JEP 370)
Provides a way to safely and efficiently access memory outside the Java heap β like native memory.
Useful for high-performance applications or integrations with C libraries.
7. πΉ ZGC and Shenandoah GC Improvements
- ZGC now supports all Linux/x64 configurations.
- Shenandoah is integrated with JDK builds (no longer external).
π Summary Table
Feature | Description | Status |
---|---|---|
Switch Expressions | Return values from switch
|
β Final |
Text Blocks | Multi-line strings | π§ͺ Preview 2 |
Records | Immutable data classes | π§ͺ Preview |
Pattern Matching (instanceof ) |
Inline type cast in condition | π§ͺ Preview |
Helpful NPEs | Clear null pointer messages | β Final |
Foreign Memory Access | Off-heap memory access | π¬ Incubator |
ZGC & Shenandoah | GC improvements | β Final |
π Note:
-
Features like Records, Pattern Matching, and Text Blocks require
--enable-preview
in Java 14.