Ubuntu – How to run a Java program in Ubuntu

compilingjava

sachin@sachin-Lenovo-G550:~$ java -version
java version “1.7.0_21″
OpenJDK Runtime Environment (IcedTea 2.3.9) (7u21-2.3.9-1ubuntu1)
OpenJDK Server VM (build 23.7-b01, mixed mode)

When I ran the above command this showed that Java is installed in my system, but when I am going to compile any Java program it gives the following error message:

sachin@sachin-Lenovo-G550:~/programs$ javac abc.java
The program ‘javac’ can be found in the following packages:
* default-jdk
* ecj
* gcj-4.6-jdk
* gcj-4.7-jdk
* openjdk-7-jdk
* openjdk-6-jdk
Try: sudo apt-get install

Please tell me how to get rid of it and run my Java program.

Best Answer

Open the terminal and run:

sudo apt-get install openjdk-7-jdk

and then compile your Java program as before with: javac abc.java. Then run it with:

java abc  ## The name of the class to be called is abc NOT abc.class

You can also substitute openjdk-6-jdk instead of openjdk-7-jdk in the first command. In Ubuntu 15.10 and newer, you can also substitute openjdk-8-jdk instead of openjdk-7-jdk in the first command. In Ubuntu 17.10 you can also substitute openjdk-9-jdk. In Ubuntu 17.10 and later you can also substitute openjdk-11-jdk.

In Java 9 and letter, Java has a built-in shell that can run blocks of Java code directly from the terminal without compiling the Java code first, jshell, defined in JEP 222. To start jshell from the terminal type jshell.

$ jshell
|  Welcome to JShell -- Version 11.0.7
|  For an introduction type: /help intro

jshell>

To exit from jshell type /exit.

Related Question