How to edit, compile, and run Java programs

Edit me

How do I edit, compile and run Java programs?


Open up your favorite text editor, (gedit, emacs, or vi, refer to this quick manual question 1), create a file with .java extension. For example, you could create a simple java program like the following:

public class Test
    public static void main(String[] args)
        System.out.println("Hollow World!");

Save the file with the name: Please note your source file must have the same name as the class name (plus the .java file extension) if the class has the public access modifier. Also, by convention, your class name should start with an upper case letter.


Our java installation is in /usr/local/jdk1.5.0/bin, which requires being included in user's PATH environment variable. If you are a computer major student, your path should be already set up for using those java tools, (if not, refer to quick start HowTo manual question 2 to set up your property files to include java and other necessary executables).

Within the directory that you saved, type: javac source_file. For example, you type:


This will create a java bytecode of our program in the same directory as the source code, named: "Test" to be ready to execute by JVM.

Optionally, you could use javac options to specify your source path and output directory for that particular invocation, for example:

javac -sourcepath ~/ -d classes

Suppose you are not exactly in your source file directory which is your home directory and you want the compiled file put in the classes directory.


To run your program, the JVM needs to know where to load your bytecode. There are two ways to tell the JVM the class path. You can set the path in your CLASSPATH environment variable or specify the class path with the "-cp" command-line option.

For example, you could run your program with:

java Test


java -cp . Test

At the prompt if our bytecode or classes file in the current working folder (that is the case for us since we did not direct the output to a different place). The only difference between those two commands is for the former, your current directory has already included in your CLASSPATH, for the latter is not.

You could set up the CLASSPATH for the current session with whatever the CLASSPATH value, for our example, we could do the following to dynamically set up the CLASSPATH variables and execute our program:


This sets our current directory in the classpath, and appends whatever the original classpath was.

Now, the CLASSPATH issue is out of our way, we could just simply type:

java Test run our sample java program. Here comes the ubiquitous first exposure of programming:

Hello World!