Search code examples
javavisual-studio-codejavacjava-14

How to fix Java UnsupportedClassVersionError


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?


Solution

  • This error is telling you that your class was compiled at a higher version of Java than the version you are trying to run with. More specifically, in this case, you compiled your class with Java 15 and try to run it with Java 14.

    Depending on your situation, you have two ways to resolve the error: compile your code with an earlier version of Java, or run your code on a newer Java version.

    Fix via the Command Line. If you're ready to move entirely to a newer JDK, you should download the newer version and make sure your PATH and JAVA_HOME environment variables are set appropriately. Assuming you have Java 15 JRE, you can run your code with the java command packaged with it.

    IntelliJ IDEA. You can also control the version of Java you're using for compiling and running in IntelliJ IDEA. Go to File -> Project Structure… -> Project Settings -> Project and change your Project SDK and Project language level. Next run your project on the newer JRE: go to Run -> Edit Configurations… and change your JRE to 15. Now, when you run your project, it will run with the Java 15 JRE.