This page will cover how to compile and run Java files. This is also covered in the Communicating with Machines lesson.

You need to have Java installed. If you haven’t yet, please follow the tutorials:

To make sure it is installed correctly, run the following command:

javac -version

Make sure it doesn’t return something along the lines of “javac is not recognized as internal or external command” or “command not found: javac”.





Create the example file to follow this tutorial

NOTE: depending on where you do this, you may require admin privileges!

  1. Create folder called HelloWorld (notice there are no spaces!). This can be done my typing the following command into your terminal:
     mkdir HelloWorld
    
  2. Create a text file called HelloWorld.java, add the following code, and save it:
     class HelloWorld {
         public static void main(String[] args){
             System.out.println("Hello World!");
         }
     }
    

Alternatively, you can download it here:

Download ‘HelloWorld.java’


Compiling and running Java files

The following will use the above HelloWorld.java file.

Locate the file to compile, and cd (change directory) into the folder containing the said file:

cd HelloWorld

"Find Folder"!


To compile, use the following command:

javac NAME_OF_YOUR_FILE.java


This will create a *.class file:

"Compile Java Program"


To run the class file, use the following command:

java NAME_OF_YOUR_CLASS

"Run Java File"!