7

I came across this amazing topic on https://www.baeldung.com/java-pattern-matching-instanceof. But when I try to run the following code, it throws compile time error:

if(obj instanceof String s) {
    System.out.println(s);
}

The error says:

Patterns in 'instanceof' are not supported at language level '14'

Error:(36, 34) java: pattern matching in instanceof is a preview feature and is disabled by default. (use --enable-preview to enable pattern matching in instanceof)

But I have Java 14 installed.

  • Please edit your question. Include the compile time error's full message and what you didn't understand from it. Change your title to reflect the actual issue, not the concepts involved (which can be added as tags). – Sotirios Delimanolis May 23 '20 at 13:29
  • Include the entire error message. Assuming you're compiling this in Intellij, the message continues in both the "Quick Fixes" subtab and in the "Build" window. If you're not compiling in Intellij, include the entire error message you're seeing from `javac` or the entire error message you're seeing in Eclipse (or whatever else compiler you're using). – Sotirios Delimanolis May 30 '20 at 18:24
  • I never compiled it originally otherwise I would have known the actual cause lol –  May 30 '20 at 18:26

2 Answers2

18

This is a preview feature in Java 14, see JEP 305 and JEP 375. To enable this, compile your class with:

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

And now you can do:

java MainClass --enable-preview

Example of instanceof:

Object o = "Hello World!";
if (o instanceof String s) {
    // no explicit type casting
    s = s.replaceFirst("World", "Java"); // No compile time issues
    System.out.println(s);
}

Another example copied from JEP:

if (obj instanceof String s && s.length() > 5) {.. s.contains(..) ..}

UPDATE

Since Java 16 the "Pattern Matching for instanceof" is a fully finalized feature (i.e. not a preview anymore). So when using Java 16 or newer there is no need to separately enable this feature as it will be enabled out of the box.

See JEP-394 for the details.

RubioRic
  • 2,442
  • 4
  • 28
  • 35
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • 2
    I think you mean _"when using Java 16 or **newer** there is no need..."_ instead of _"when using Java 16 or **older** there is no need..."_, right? – skomisa May 08 '23 at 05:45
3

This feature is finalized in Java 16 (JEP 394). For the below versions, refer this link to enable this preview feature from IDEs such as IntelliJ, Eclipse, and STS.

Praj
  • 451
  • 2
  • 5