Article

Java and the Command Line

A brief overview of running Java through the command line.

While there are many IDEs with built-in execution capabilities (Eclipse and IntelliJ for example), Java can also be run directly from the command line.

In this article, we’ll cover how to download and run Java on your personal computer, as well as how to utilize the String[] args parameter of the main method.

Downloading Java

Java is available (for free) through Oracle’s website. You can find the appropriate version for your computer here. If you have trouble downloading Java, take a look at Oracle’s help page.

Compiling Java

Before you can run the program from the command line, you must compile it. Open your terminal or command prompt (depending on OS), and navigate to the directory where the file you want to run is located. Once there, use javac and the filename to compile:

javac MyClass.java

(If you’re new to the command line or need a refresher on navigation, take a look at our command line cheatsheet for more guidance.)

This creates the .class file that can be executed. However, if there are any bugs found in your program, they will be flagged at this point, and the executable .class file will not be created. You won’t be able to run the file until it compiles with no issues.

Running Java

Once you have your executable file, use java and the name of the class to run it:

java MyClass

Note: Do not include the .java or .class suffixes, only use the name of the class.

Let’s say we had the following Java class:

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } }

We would compile this using:

javac HelloWorld.java

Then run it using:

java HelloWorld

It would output the following:

Hello world!

main Method Parameters

Each Java class must have a main method, and every main method contains the parameters String[] args, but what does that mean?

args is an array of Strings that is passed to the program when it’s run. (Click here for a refresher on arrays in Java.) We don’t need to pass anything in, but we can if we want to. For example, we can edit our HelloWorld class to use elements from args:

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world, my name is " + args[0] + "!"); } }

Note that we access the elements of the args array the same way we would access the elements of any other array.

Let’s use the new HelloWorld class to introduce ourselves! First, we’ll compile our class the same way we did before:

javac HelloWorld.java

Next we’ll run it. However, this time, we’ll add in a String argument:

java HelloWorld Batman

The program will output the following:

Hello world, my name is Batman!

Ready to Learn More?

Find the course that's right for you! Explore our catalog or get a recommendation.
Course

Java for Programmers

Intermediate

Career Path

Code Foundations

Beginner friendly

15 Lessons