How to Run Java .Class Files From Command Line

Sheeraz Gul Feb 02, 2024
How to Run Java .Class Files From Command Line

Executing a Java class file from the command prompt is an easy process; make sure you have installed the JDK and follow the process mentioned in this article. This tutorial demonstrates how to execute Java class files from the command line.

Execute Java Class From the Command Line

Java class files are compiled Java files that the Java Virtual Machine executes. Let’s try to run the following Java class through the command prompt.

package delftstack;

public class Demo {
  public static void main(String[] args) {
    System.out.println("Hello! This is demo.class example from Delftstack.");
  }
}

Follow the steps one by one:

  • To execute the .java class files, open the Windows command prompt or the macOS terminal.

    CMD on Windows

  • Go to the Demo.java file directory or any directory where you want to run a Java file.

    CMD Change Directory

  • Run javac <filename>, in our case javac Demo.java.

    CMD Run Java File

  • The next step is to run the class; enter java Demo.java in the command prompt; this should output:
    Hello! This is demo.class example from Delftstack.
    

    CMD Output of Java File

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook