Using Java From the Command Line
What you need
• the Java JDK (contains the compiler), either the standard version installed on your computer or
a portable version on your flash drive
• the Java JRE (runtime environment) installed on the computer itself or the portable version on
your flash drive. Chances are the computer you are using already has the JRE available, so you
should rarely need a portable version.
• Access to the command line interface on the computer (terminal).
• A plain text editor. Recommendations are:
◦ Notepad++ for computers running Windows
◦ gEdit (Gnome environment) or Kate (KDE environment) for computers running Linux
Other plain text editors will work but the recommended ones can do syntax highlighting, which
is very helpful when creating your source code files.
Getting set up
Generally on a Windows system, you will need to make sure your path is set correctly before you can
use Java from the command line. To do so:
1. Use your plain text editor to create a file named js.bat
2. Paste the following two lines of code into that file:
3. Save and close the file.
This is not usually necessary on other systems.
Creating a Java Program
Use your plain text editor to enter and save your Java source code. Make sure that you give the file the
exact same name, including case of letters, as your Java class, and that the file extension for your file is
.java, i.e. filename.java. Save your file.
Compiling Java Programs
Open up your command line interface (the Terminal). On Windows systems, the Terminal can usually
be found by going to Start->Programs->Accessories. On Linux systems using GNOME, it is available
from Applications ->Accessories. Note that it is NOT necessary to run the Terminal as root!
If you are on a Windows system, run your js.bat file first thing.
Make sure your command line prompt indicates you are in the directory where your source code file is
located. Then compile your program using the following command:
If your source code contains errors, you will see one or more error messages in the terminal window.
You will need to use your plain text editor to locate those errors and fix them before continuing. Repeat
the previous step until you get no errors when you issue the javac command.
Running Java Programs
Once your program has compiled cleanly, there will be a bytecode file in the same directory as the
source code file. This bytecode file will have the same file name as the source code file, but will have a
file extension of .class instead of .java.
To run your program, use the following command:
Note that you do NOT type the file extension here!
You should see your output appear in the terminal window if your program is a console application, or
in a new window if it is a GUI application or applet.