You are here
Home > java > Core Java >

What are Preview Features in Java?

Preview Features in JavaIn every new version of Java, one word is definitely seen and that is ‘Preview Feature’. Some of us know about it, but some people like beginners don’t know. Even if one who knows, there is no proper clarity about it. Therefore, in this article, we will discuss in detail all about ‘Preview Features in Java’.

Learning Preview Features in Java helps developers stay updated with new improvements before they become permanent. It allows early testing, reduces future migration efforts, and improves coding efficiency. Developers can also provide feedback to shape Java’s future. Understanding these features ensures better decision-making and keeps you ahead in the Java ecosystem.

Table of Contents

What are Preview Features in Java?

Preview features are new functionalities introduced in Java that are not yet finalized. They are made available in a specific Java version for developers to try out, experiment with, and provide feedback. These features are not permanent and may change or be removed in future releases based on the feedback received. They allow developers to test new ideas and improvements before they are officially added to the language.

They are fully implemented but kept optional so that developers can try them out and give feedback. Based on community feedback, these features might be modified, removed, or become permanent in later releases.

Why Does Java Have Preview Features?

Java follows a strict evolution process, ensuring new features don’t introduce instability. Preview features serve the following purposes:

1) Gather developer feedback before making a feature permanent. Developer’s feedback is important and can help shape the future of Java.

2) Allow early adopters to test new functionality in real-world applications. Developers get to use and experiment with new features before they are finalized.

3) Prevent unnecessary breaking changes by fine-tuning features before final adoption.

What is the Lifecycle of a Preview Feature?

Below is a textual representation of the lifecycle of a Preview Feature in Java.

Start

Introduce Preview Feature

Feedback Collection

Evaluation of Feedback

Decision Point
├── Positive Feedback → Becomes a Permanent Feature → End
├── Needs Improvement → Modified → Feedback Collection
└── Negative Feedback → Removed → End

Java Preview Feature Lifecycle

1) Start

  • A new feature is introduced as a Preview Feature in Java.

2) Feedback Collection

  • Developers and users test the preview feature.
  • Feedback is collected from the community, developers, and stakeholders.

3) Evaluation of Feedback

  • Analyze the feedback to determine the feature’s success and areas for improvement.

4) Decision Point

Based on the feedback, decide the next step:

  • Positive Feedback: Proceed to Become a Permanent Feature.
  • Needs Improvement: Proceed to Be Modified.
  • Negative Feedback/Doesn’t Meet Expectations: Proceed to Be Removed.

5) Becomes a Permanent Feature

  • If the feedback is positive, the feature is finalized and included as a permanent part of Java.
  • End of the process.

6) Modification

  • If improvements are needed, the feature is updated or refined.
  • Return to Feedback Collection for further evaluation.

7) Removal

  • If the feature doesn’t meet expectations or receives negative feedback, it is removed from Java.
  • End of the process.

How to Enable Preview Features?

To use preview features in our Java program, we need to explicitly enable them. Since preview features are not enabled by default, we need to explicitly allow them during compilation and runtime. This is done using special command-line options when compiling and running your code.

If we don’t enable the –enable-preview flag, the compiler and JVM will reject any preview feature usage.

Compiling with Preview Features

When compiling a Java program that uses preview features, use the –enable-preview flag along with the -source and –release options. For example:

javac --enable-preview --source 20 MyProgram.java

Here, –source 20 tells the compiler to use Java 20 syntax, and –enable-preview enables the preview features.

Running with Preview Features

When running the program, we also need to enable preview features using the –enable-preview flag:

java --enable-preview MyProgram

Example: Using a Preview Feature

Let’s say Java 20 introduces a new preview feature called Pattern Matching for Switch. Here’s how we can use it:

public class PatternMatchingExample {
    public static void main(String[] args) {
        Object obj = "Hello, Java 20!";

        // Using pattern matching in switch (preview feature)
        String result = switch (obj) {
            case String s -> "It's a string: " + s;
            case Integer i -> "It's an integer: " + i;
            case Double d -> "It's a double: " + d;
            default -> "It's something else!";
        };

        System.out.println(result);
    }
}

Explanation

  1. Pattern Matching: The switch statement can now directly check the type of the object (obj) and bind it to a variable (s, i, or d).
  2. Preview Feature: This syntax is a preview feature in Java 20, so we need to enable it using the –enable-preview flag.

Steps to Run

  1. Save the code in a file named PatternMatchingExample.java.
  2. Compile it with preview features enabled:
    javac --enable-preview --source 20 PatternMatchingExample.java
  3. Run the program:
    java --enable-preview PatternMatchingExample

Key Preview Features in Recent Java Versions (With Examples)

Let’s now explore some major preview features introduced in Java and see them in action.

Pattern Matching for instanceof (Introduced in Java 14, Finalized in Java 16)

Before (Java 13 and earlier)

Before pattern matching, we had to manually cast an object after checking its type:

With Pattern Matching (Java 14 Preview Feature)

Java introduced pattern matching for instanceof, eliminating the need for explicit casting:

Simpler, cleaner, and avoids redundant casting.

Records (Introduced in Java 14, Finalized in Java 16)

Before (Java 13 and earlier)

To create an immutable data class, you had to write a lot of boilerplate code:

With Records (Java 14 Preview Feature)

With the record keyword, you can now declare the same class in one line:

Auto-generates constructor, getters, toString(), equals(), and hashCode().

Switch Expressions (Introduced in Java 12, Finalized in Java 14)

Before (Traditional Switch Case)

With Switch Expressions (Java 12 Preview Feature)

More concise and allows returning values directly.

Virtual Threads (Introduced in Java 19, Preview in Java 20)

Before (Traditional Threads)

With Virtual Threads (Java 19 Preview Feature)

Lightweight threads, ideal for high-concurrency applications.

String Templates (Preview in Java 21, Java 22)

Before (Using + for Concatenation)

With String Templates (Java 21 Preview Feature)

More readable and prevents mistakes in complex string formatting.

Best Practices for Using Preview Features

1) Use in Development, Not in Production – Since preview features may change, avoid using them in production systems.

2) Stay Updated with JEPs – Check OpenJDK JEPs to track feature changes.

3) Participate in Providing Feedback – Report issues or suggestions via bugs.java.com.

4) Enable Preview Features Explicitly – Always compile and run with –enable-preview.

5) Plan for Migration – If a feature is modified in the next JDK version, be ready to refactor your code.

How to Provide Feedback?

Your experiences with preview features are valuable. If you encounter bugs, you can report them at the Java Bug Database. For more in-depth feedback, consider joining discussions on the OpenJDK mailing lists, which are often linked in the feature’s JDK Enhancement Proposal (JEP) page.

If you experiment with preview features and share your feedback, you contribute to the evolution of the Java language and ensure it meets the needs of its diverse developer community.

Important Notes

1) Not for Production: Preview features are not stable and should not be used in production code.

2) Feedback: If you use preview features, consider providing feedback to the Java team to help improve the feature.

3) Future Changes: Preview features may change or be removed in future Java versions.

FAQs

What happens if I try to use a preview feature without enabling it?

If you use a preview feature without –enable-preview, the compiler and JVM will reject your code and throw errors.

Example:

record Person(String name, int age) {} // Java 14 Preview Feature

🔴 Error (if preview not enabled):

error: records are a preview feature and are disabled bydefault

Do preview features become permanent in later Java versions?

Not always. A preview feature can:

Become a permanent feature (if the feedback is positive).

Be modified (if improvements are needed).

Be removed (if it doesn’t meet expectations).

For example:

  • Records (Preview in Java 14 → Finalized in Java 16).
  • Module Import Declarations (Preview in Java 23, still under second Preview in Java 24).

Can I use Preview Features in production code?

No. Since preview features are not finalized, they may change in future versions. Using them in production can lead to compatibility issues when upgrading to a new Java version.

Use preview features for testing and experimentation only.

What are some examples of Preview Features that became permanent in Java?

Many Preview Features have successfully transitioned into standard Java features. Here are some examples:

Feature Preview in Finalized in
Records (record) Java 14, 15 Java 16
Text Blocks (“”” syntax for multi-line strings) Java 13, 14 Java 15
Pattern Matching for instanceof Java 14, 15, 16 Java 16
Sealed Classes (sealed keyword) Java 15, 16 Java 17
Pattern Matching for switch Java 17, 18, 19, 20 Java 21
Virtual Threads (Project Loom) Java 19, 20 Java 21

These features started as previews, were improved based on developer feedback, and became permanent parts of Java.

Are Preview Features the same as Incubator Features?

No, they are different:

Feature Type Purpose
Preview Feature Fully implemented but not yet finalized.
Incubator Feature An experimental feature not part of standard Java, meant for testing.

Example:

  • Foreign Function & Memory API started as an Incubator Feature before moving to Preview.

How long does a feature stay in Preview?

It varies, but typically a feature stays in preview for at least one release cycle. Some features may go through multiple preview cycles before finalization.

Can I use preview features in libraries or frameworks?

It’s not recommended because preview features might change or be removed, leading to compatibility issues when a new Java version is released.

If you still want to use them in libraries, clearly document that your library requires preview features. Expect potential breaking changes in future Java versions.

Where can I find official documentation on Preview Features?

The best sources are:

Can I disable Preview Features after enabling them?

Yes. If you compiled code with –enable-preview, but later remove the flag, your code might stop working.

Example:

  1. Compile with preview:
    javac --enable-preview --release 21 MyClass.java
  2. Run without preview (will cause an error):
    java MyClass
    

What happens to code written using a preview feature if it is removed in the next Java version?

If a preview feature is removed or modified, your code will no longer compile or run in the newer version.

For example, if you used String Templates in Java 21 (preview), but suppose that the syntax changes in Java 22, you’ll have to update your code to match the new syntax.

How do I provide feedback on Preview Features?

You can share feedback by:

Are preview features different from experimental features?

Yes. Experimental features are hidden behind special flags and are not part of the Java standard.

Feature Type Enabled By Default? Stability
Preview Features ❌ No (must enable –enable-preview) May become permanent
Experimental Features ❌ No (hidden, needs JVM flags) Highly unstable

Example of an experimental feature:

java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC

(ZGC garbage collector was experimental before becoming stable in Java 15)

Can I mix Preview Features with regular Java code?

Yes, but all code using preview features must be compiled with –enable-preview.

Example (Allowed)

public record Person(String name, int age) {} // Java 14 Preview Feature

Compile:

javac --enable-preview --release 14 Person.java

Example (Not Allowed)

// Using a preview feature without enabling preview mode
record Person(String name, int age) {}

🔴 Error:

error: records are a preview feature and are disabled bydefault

Can a preview feature change in the next Java version?

Yes, preview features can be modified, removed, or finalized in future Java versions based on community feedback. That’s why they require explicit enabling.

How long does a feature stay in preview mode?

A feature typically remains in preview for one or more releases, depending on the feedback received. Some features go through multiple preview cycles before becoming permanent.

Where can we check which features are in preview?

We can check the latest preview features in the Java SE Release Notes or the OpenJDK JEP (JDK Enhancement Proposal) Index at:
https://openjdk.org/jeps/0

Do all Java versions have preview features?

No, not every Java version introduces new preview features, but many recent releases (e.g., Java 14, 15, 16, 19, 21, 22, 23, 24 etc.) have included them.

What are some risks of using Preview Features?

1) They may change in future releases, which may require code refactoring.

2) They might be removed entirely, and can make the code incompatible with newer Java versions.

3) They are not supported in production environments.

Conclusion

Preview features allow Java developers to explore upcoming enhancements before they become standard. They provide a great way to experiment, give feedback, and influence the future of the Java language. With careful adoption, they can significantly improve your development experience and ensure your codebase stays modern and efficient.


Source: https://docs.oracle.com/en/java/javase/20/language/preview-language-and-vm-features.html#JSLAN-GUID-5A82FE0E-0CA4-4F1F-B075-564874FE2823


You may also go through:  Java Features After Java 8.

Leave a Reply


Top