How to fix Java UnsupportedClassVersionError

breadman0 picture breadman0 · Nov 8, 2020 · Viewed 9k times · Source

I've run into this error a few times trying to brush up on my Java. Looked up solutions on the internet and most suggestions were to compile or run the file with a flag/option argument to specify the correct interpreter version. My question is, is there a more permanent solution to this? (im using vscode. Guessing there is something i can add to my settings.json file in the workspace- but what?)

Error: LinkageError occurred while loading main class com.example.demo.DemoApplication
        java.lang.UnsupportedClassVersionError: com/example/demo/DemoApplication has been compiled by a more recent version of the Java Runtime (class file version 59.65535), this version of the Java Runtime only recognizes class file versions up to 58.0

here is my version details

$ java --version
java 14.0.2 2020-07-14
Java(TM) SE Runtime Environment (build 14.0.2+12-46)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.2+12-46, mixed mode, sharing)

Id like to not have to use flags whenever I compile and run a java file from the command line. Bonus points to you if you can explain why this problem happens in the first place? back when i learned java, you used to have to download and install the JRE and JDK separately. I can understand mistakenly downloading incompatible versions, but now it seems the JRE comes prepackaged with the JDK. How is it possible to have incompatible versions of the compiler and interpreter if this is the case?

Answer

Molly Wang-MSFT picture Molly Wang-MSFT · Nov 9, 2020

java.lang.UnsupportedClassVersionError: com/example/demo/DemoApplication has been compiled by a more recent version of the Java Runtime (class file version 59.65535), this version of the Java Runtime only recognizes class file versions up to 58.0 Set the JDK the same one when you compile and run the project:

That's to say, your file was compiled by JDK15, but the current runtime, which is also installed on your machine is JDK14. The dismatch of build and compile jdk version caused this error.

There're two important configurations to correctly configure your environment and project: java.configuration.runtimes and java.home. The former specifies options for your project's execution environment; the latter specifies your language server's execution environment.

You've installed JDK14, set the above two settings to use it can solve this error.

"java.home": "\PATH TO JDK14\",
"java.configuration.runtimes": [
    {
        "name": "JavaSE-14",
        "path": "\PATH TO JDK14\",
        "sources": "\PATH TO JDK14\lib\src.zip",
        "javadoc": "https://docs.oracle.com/en/java/javase/14/docs/api",
        "default": true
    },      
],

Cleaning the Java Language Server Worspace and reload the window in VS Code, then run again.

More information about java.configuration.runtimes and java.home, please refer to Configure JDK.