How to Run Java from Command-line in Linux?

Java is an object-oriented high-level programming language. It is an independent platform that can be easily run on Windows, macOS, and Linux. The main advantage of java is reliability, as it can be easily moved from one system to another. In addition, it is very easy to debug, write and use in contrast to other programming languages

This post provides the possible ways to run Java from the command line in Linux.

Prerequisites: Install Java Development Kit (JDK)

The execution of the Java program requires the “Java Runtime Environment” in the Linux system. It is not pre-installed in most Linux distributions but can be installed using the following command on the terminal:

$ sudo yum install java-1.8.0-openjdk           # For CentOS/RHEL
$ sudo dnf intsall java-1.8.0-openjdk.x86_64    # For Fedora
$ sudo apt install default-jdk                  # For Debian/Ubuntu-Based

The “default-Jdk” has been successfully installed on the current working Linux system

For more verification check its version by running the “java” version command in the terminal as shown in the image:

$ java --version

The “openjdk” has been located in the system with version “11.0.17”.

How to Run Java from Command-line in Linux?

To run the “java” from the command line, follow the step-by-step guidelines below:

Step 1: Create the Java Program

Firstly, create or write the Java program in any test editors with the “.java” extension. In this scenario, the “” file is created in the “nano” default editor having the following source code:

class FirstJava{
    public static void main(String args[]){
     System.out.println("Welcome to Website");

Save the file “Ctrl+S” and exit it “Ctrl+X”.

Note: The Java file name and the public class name must be the same because the JDK identifies easily that it is the entry point.

Step 2: Compile the Java Program

Now, use the “javac” tool to compile the java program that converts the source code into the byte code. Use the “javac” command followed by the “” file name to compile it:

$ javac

The “” has been compiled successfully, and the “FirstJava.class” file has been created that contains the byte code of our Java program:

$ ls -l

Step 3: Execute the Java Program

Run the compiled “FirstJava” program without specifying the extension “.java”. This is because the “java” command automatically fetches out the compiled file and executes it:

$ java FirstJava

The “FirstJava” has been executed in the terminal and displays its output “Welcome to Website”.


In Linux, the “default open JDK” tool is used to run the java program from the command. This tool converts the source file to the byte code and creates its “.class” file. After that, the “java” command executes the compiled source file in the terminal. This post has illustrated the complete process of running java from the command line in Linux.