How to compile and run Java classes with Preview Features?

Giorgi Tsiklauri
2 min readSep 7, 2021

--

TL; DR:

You use:

  • javac --enable-preview --source x ClassFile.java for compiling the file with preview features (where “x” is the version of Java you’re compiling),
    and
  • java --enable-preview ClassFile for running compiled file.

The other day, I tried to run the Java 12 code, with the Preview Features, in my latest IntelliJ IDEA. This is what I got:

Switch Expression in Java 12

with the tooltip message:

'switch' expressions are not supported at language level '12'

I was like..

what? but switch expressions are available as preview features in Java 12!

I then asked the question on Stack Overflow, on which, I received the comment:

Once a final JDK with these features is released, we no longer support a preview of it in the previous JDK versions.

So, as preview features become part of the newer JDKs, IntelliJ IDEA drops the support for those features in those previous levels (versions) of the language, which, by specification have those preview features available; and that’s because (citation) “It’s the cost of maintenance for us and the cost for slower parser/highlighting/refactoring/etc”.

As you can see, this drop-down doesn’t include anymore “Java 12 (Preview Features)”, “Java 13 (Preview Features)” and so on:

This, in my humble opinion and understanding, is a very wrong and unpleasant policy #JetBrains have incorporated with #IntelliJIDEA.

By the way, it seems like, #EclipseFoundation is doing the same for #Eclipse.

I elaborate on reasons in the SO post I’ve linked above, and here, where I ask to return the support for Preview Features for all the Java Language versions, in order to not make engineers, who use different JDKs, to have several different IntelliJ IDEAs installed and keeping the track of which IDEA version supports which Preview Features of which Java. It will be a real mess and abundance. Yes, I think, that’s really messy, unpleasant and even irresponsible decision, and because of this, you might want to know how to compile and run different versions of Java language, in your favourite shell or terminal.

--

--

Giorgi Tsiklauri

Software engineer, architect, lecturer; long while w/ computers and music; interested in software design, computer networks, composition, security and privacy.