In this blog, How to run Java on Visual Studio Code on Ubuntu is shown.
▼1. Run Java using Visual Studio Code on Ubuntu
Visual Studio Code is the developer tool provided by Microsoft. Visual Studio Code works on both Windows and Linux OS. in this case, VS Code is used on Ubuntu.
▼2. Prerequisites
2-1.Install Ubuntu Ubuntu 20.04.5 LTS
2-2. Setup Visual Studio Code
2-3. Install Java Extension Pack
2-4. Install JDK (OpenJDK 15)
In this case, jdk-15.0.2+7 is under /home/user/Downloads/ path.
2-5. Set Environment variables for java.configuration.runtimes and java.home
(e.g)
{
"java.home":"/home/user/Downloads/jdk-15.0.2+7",
"java.configuration.runtimes": [
{
"name":"JavaSE-15",
"path":"/home/user/Downloads/jdk-15.0.2+7"
}
]
}
▼3. Show Hello World by Java
3-1. Create Folder “JavaTest” and Hello.java file
Getting Started with Java in Visual Studio Code
public class Hello{
public static void main(String[] args){
System.out.println("Hello World!!!");
}
}
3-2. Press F5 key on VS Code or Click Run Java
Output in Terminal is below.
(e.g)
user@user2ubuntu:~/JavaTest$ cd /home/user/JavaTest ; /usr/bin/env /home/user/Downloads/jdk-15.0.2+7/bin/java --enable-preview -XX:+ShowCodeDetailsInExceptionMessages -Dfile.encoding=UTF-8 -cp /home/user/.config/Code/User/workspaceStorage/33dce62422c26202e52d97a8fbad1d66/redhat.java/jdt_ws/JavaTest_52922a16/bin Hello
Hello World!!!
3-3. Create Jar file and run this jar
Pressing [Shift]+[Ctrl]+[p] on VS Code and choosing “Java:Export jar” option to generate JavaTest.jar file under /home/user/ path
Lightweight Mode, Maven Support, Java Package, and Dependency Management in Visual Studio Code
3-4. Run the generated jar file in the terminal
“Hello World!!!” is shown in the the terminal as below.
(e.g)
user@user2ubuntu:~/JavaTest$ ../Downloads/jdk-15.0.2+7/bin/java --enable-preview -jar /home/user/JavaTest/JavaTest.jar
Hello World!!!
(*) –enable-preview
Java –enable-preview option can avoid the following error message.
Error: LinkageError occurred while loading main class Hello
java.lang.UnsupportedClassVersionError: Preview features are not enabled for Hello (class file version 59.65535). Try running with ‘–enable-preview’
java – Run a .jar with –enable-preview option – Stack Overflow
That’s all. Have a nice day ahead !!!