How to enable Java 21 preview features
Enable preview features in Java 21
To enable Java 21 preview features, you must follow a two-step process:
- Compile your Java 21 code with the
--release 21 --enable-preview
flag. - Run your Java 21 code with the
--enable-preview
flag.
If you miss either step, you’ll encounter both compile-time errors and runtime errors.
Java 21 preview feature commands
To test out Java 21’s new instance main methods and unnamed classes, I created a simple Java file named BlackJackHelloWorld.java. The command to compile the code containing the Java 21 preview features is as follows:
javac --release 21 --enable-preview BlackJackHelloWorld.java
To run the code, use the following command:
javac --release 21 --enable-preview BlackJackHelloWorld.java
New Java 21 features
The September Java 21 release is scheduled to include a variety of preview, GA and incubating features, including the following:
- Vector API (Sixth Incubator).
- String templates (Preview).
- Unnamed patterns and variables (Preview).
- Unnamed classes and instance main methods (Preview).
- Scoped values (Preview).
- Foreign function & memory API (Third Preview).
- Structured concurrency (Preview).
Along with finalized features including sequenced collections and virtual threads, Java 21 has become a highly anticipated LTS release.