Sub topic 12
Which Java version you need
This chapter assumes you can write a type pattern with instanceof, you know what a binding variable is, and you can run javac and java or a Maven or Gradle build. Here you will find out which Java release lets you use the feature, how it was previewed before release, and how to configure a project that builds on the right version.
The short answer
Pattern matching for instanceof is a standard feature from Java 16. Java 16 was not a long-term support (LTS) release, so most teams meet the feature on Java 17, the next LTS. Java 21 and Java 25 are later LTS releases and also include it.
| Java version | Status of `instanceof` patterns | Notes |
|---|---|---|
| 8, 11 | Not available | The code does not compile. |
| 14 | Preview (JEP 305) | Needs `--enable-preview`. |
| 15 | Second preview (JEP 375) | Needs `--enable-preview`. |
| 16 | Final (JEP 394) | Works without flags. |
| 17 (LTS) | Final | First LTS release with the feature. |
| 21 (LTS) | Final | Adds record patterns and switch patterns as final features. |
If your project targets Java 11 or earlier, you have to keep the check-then-cast idiom. Nothing in the language lets you backport the syntax.
How the feature reached Java 16
The language team often ships a feature as a preview first. A preview feature is fully specified and implemented, but it can still change or be removed, and the compiler refuses to use it unless you opt in. This gives the team time to collect feedback.
Type patterns in instanceof went through two previews before they became final.
- Java 14 introduced the syntax
o instanceof String sas a preview. - Java 15 previewed it again with small refinements.
- Java 16 made it permanent and changed two rules.
The two rules that changed in Java 16 matter if you read older articles.
- Binding variables are no longer implicitly final. In the previews you could not assign to
s. From Java 16 you can, as with any local variable. - A pattern whose type is already guaranteed was an error. In the previews,
str instanceof String swas a compile-time error whenstralready had typeString, because the test is always true except fornull. Java 16 kept that error. Later releases removed it, so the same line compiles in Java 21.
Checking which Java you are running
Before you debug a mysterious compile error, find out which compiler you are using. Many machines have several JDKs installed, and the java on your path may not be the one your build uses.
java -version
javac -versionThe two versions can differ. If javac -version prints javac 11.0.x, the pattern syntax will fail even if the java launcher is newer.
The error messages are a useful clue. On a compiler older than 14 you typically see an error such as this one.
Main.java:4: error: ';' expected
if (o instanceof String s) {
^The old compiler parses o instanceof String as a complete test and then does not know what to do with s. This message does not mention patterns, so the version is the first thing to check.
On Java 14 or 15 without the flag, the message names the problem directly.
error: pattern matching in instanceof is a preview feature and is disabled by default.
(use --enable-preview to enable pattern matching in instanceof)A program that tests the version
This small program prints the runtime version and uses a type pattern. On Java 16 or later it compiles and runs without flags.
public class VersionCheck {
public static void main(String[] args) {
Object o = Runtime.version();
System.out.println("Running on feature release " + Runtime.version().feature());
if (o instanceof Runtime.Version v && v.feature() >= 16) {
System.out.println("Pattern matching for instanceof is a final feature here.");
}
}
}Compile and run it like this.
javac VersionCheck.java
java VersionCheckThe Runtime.Version.feature() method exists since Java 10, so the version query itself is fine on older JDKs. Only the pattern fails to compile there.
Compiling for a specific release
Compiling with a newer JDK does not automatically produce code that runs on an older JVM. Use the --release option to say which Java version you target. The compiler then checks both language features and library APIs against that version.
javac --release 17 VersionCheck.javaIf you write --release 11 and your source contains a type pattern, the compiler rejects it even though the JDK itself is newer. This is the behavior you want, because it catches the problem at build time instead of on a production server running Java 11.
The older options -source and -target set the language level and class file version separately. They do not check library APIs, so prefer --release whenever it is available.
Preview mode on Java 14 and 15
Only use this section if you are stuck on one of those two releases, which are no longer supported. The flag must be given to both the compiler and the runtime.
javac --release 15 --enable-preview VersionCheck.java
java --enable-preview VersionCheckThe compiler prints a note that the file uses preview features. Preview class files are marked with the exact feature release. A class compiled with --enable-preview on Java 15 will not load on Java 16 or on Java 17, even with the flag. You must recompile. This is another reason not to ship preview code.
Configuring a build tool
In practice you set the version in your build file. Here is a Maven configuration that targets Java 17.
<properties>
<maven.compiler.release>17</maven.compiler.release>
</properties>For Gradle, a toolchain asks Gradle to find or download a matching JDK, so the build does not depend on whichever JDK is on the path.
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}Your IDE also has a language level setting, and it can disagree with the build file. If the editor underlines a type pattern as an error but the command-line build passes, check the project language level in the IDE.
Reassigning binding variables
Since Java 16 a binding variable can be assigned, which was an error in the previews.
static String trimmed(Object o) {
if (o instanceof String s) {
s = s.strip();
return s;
}
return "";
}This compiles on Java 16 and later, and fails with an error about assigning to a final variable in preview releases. It also affects scope. A binding variable that you reassign is still in scope where a pattern would normally put it, but reassigning it makes code harder to follow, because readers expect s to be the value that matched. Treat the variable as effectively final unless you have a reason not to.
What comes after Java 16
The feature this tutorial covers is only the first step of a larger sequence, and later steps need later versions.
- Record patterns such as
o instanceof Point(int x, int y)were previewed in Java 19 and 20 and became final in Java 21. - Pattern matching for
switchwas previewed from Java 17 and became final in Java 21.
A project on Java 17 can use type patterns in instanceof, but not record patterns or case patterns in switch. If you plan to use those, set Java 21 as your minimum.
Decision guide
- Run
javac -versionand confirm which compiler your build really uses. - If it is 16 or later, write type patterns freely and set
--release(ormaven.compiler.release, or a toolchain) to match. - If you must support Java 11 or older, use the check-then-cast idiom until you can move up.
- If you want record or switch patterns, set the minimum at Java 21.
Exercise
A library must run on Java 11 clients, and a developer builds it on JDK 21 using javac with no options. They write if (o instanceof String s) in the source. Does this build succeed, and does the result run on Java 11? What should they change?
Show answer
The build succeeds, because JDK 21 accepts the syntax with no flags. The class file is compiled for Java 21, so a Java 11 JVM refuses to load it with an unsupported class version error. The fix has two parts. Compile with --release 11 so the compiler rejects the pattern and stops the mistake at build time. Then rewrite the code with the check-then-cast idiom (if (o instanceof String) { String s = (String) o; ... }), because Java 11 has no type patterns.
Exercise
A teammate on Java 15 sees "pattern matching in instanceof is a preview feature and is disabled by default." They add --enable-preview to javac only, then run java VersionCheck and it fails. What went wrong, and what is the better long-term fix?
Show answer
The flag must also be passed to the runtime: java --enable-preview VersionCheck. The better long-term fix is to upgrade to Java 17 or later, where the feature is final and no flag is needed. Preview class files also stop loading when the JDK is upgraded, so enabling preview is only a short-term workaround.