Search code examples
javaubuntuvisual-studio-codeconfigurationjavac

How to specify Java version in VS Code?


I have created a virtual machine to run some java code in it and have specified the VM to run with java 11

ubuntu@go-v12as34df:~$ java -version
openjdk version "11.0.21" 2023-10-17
OpenJDK Runtime Environment (build 11.0.21+9-post-Ubuntu-0ubuntu122.04)
OpenJDK 64-Bit Server VM (build 11.0.21+9-post-Ubuntu-0ubuntu122.04, mixed mode, sharing)

Up until here all is ok. When I connect to the VM through nomachine or similar, all works fine.

But when I login through ssh using Visual Studio Code, this appears:

ubuntu@go-v12as34df:~$ java -version
openjdk version "21.0.2" 2024-01-16 LTS
OpenJDK Runtime Environment Temurin-21.0.2+13 (build 21.0.2+13-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.2+13 (build 21.0.2+13-LTS, mixed mode, sharing)

But this does not happen when I open VS Code through nomachine...

When I check the 'Configure Runtime for Projects' it appears the Java Version 11 as specified in my project's pom file as well so that's ok.

How can I specify the java version to be Java 11 in VS Code? I have tried the sudo update-java-alternatives but it just does not work and can't download the Java version in my main pc because it's a work pc limited by corporate IT.

Thanks!


Solution

  • First your machine must have the corresponding JDK version installed, then you can specify the JDK using the following setting:

    "java.configuration.runtimes": [
      {
        "name": "JavaSE-1.8",
        "path": "/usr/local/jdk1.8.0_201"
      },
      {
        "name": "JavaSE-11",
        "path": "/usr/local/jdk-11.0.3",
        "sources" : "/usr/local/jdk-11.0.3/lib/src.zip",
        "javadoc" : "https://docs.oracle.com/en/java/javase/11/docs/api",
        "default":  true
       },
       {
        "name": "JavaSE-12",
        "path": "/usr/local/jdk-12.0.2"
       },
       {
        "name": "JavaSE-13",
        "path": "/usr/local/jdk-13"
       }
    ]
    

    https://code.visualstudio.com/docs/java/java-project#_configure-runtime-for-projects