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.

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.