error: --enable-preview must be used with either -source or --release

Posted by Shaaf's blog on Thursday, September 7, 2023

The JDK 21 release is well underway likely to drop around September 19th, and its not GA yet. further more it provides preview features.

It was time for downloading one of the releases and giving it a try. Well I have given it a try some weeks ago so I already had it installed. e.g.

openjdk version "21-ea" 2023-09-19
OpenJDK Runtime Environment (build 21-ea+26-2328)
OpenJDK 64-Bit Server VM (build 21-ea+26-2328, mixed mode, sharing)

The fun thing though is that there are couple of very cool features that are still in preview. e.g. I tried to use the StringTemplates mentioned in the InfoQ blog

~/git/java-examples 🐠  javac StringTemplates.java                                               14:50
StringTemplates.java:6: error: string templates are a preview feature and are disabled by default.
    public static String html = STR."""
                                    ^
  (use --enable-preview to enable string templates)
1 error

To compile with features enabled. use the following example command

javac StringTemplates.java --enable-preview --release 21

And finally to run you would also want to enable the preview

~/git/java-examples 🐠  java --enable-preview StringTemplates                                    14:56
<html>
  <head>
    <title>My Web Page</title>
  </head>
  <body>
    <p>Hello, world</p>
  </body>
</html>

List of included JEPs in Java 21:

JEPTitle
430String Templates (Preview)
431Sequenced Collections
439Generational ZGC
440Record Patterns
441Pattern Matching for switch
442Foreign Function & Memory API (Third Preview)
443Unnamed Patterns and Variables (Preview)
444Virtual Threads
445Unnamed Classes and Instance Main Methods (Preview)
446Scoped Values (Preview)
448Vector API (Sixth Incubator)
449Deprecate the Windows 32-bit x86 Port for Removal
451Prepare to Disallow the Dynamic Loading of Agents
452Key Encapsulation Mechanism API
453Structured Concurrency (Preview)