DEV Community

Cover image for 3.2. Compile and run your Java program
Raghav Khanna
Raghav Khanna

Posted on

3.2. Compile and run your Java program

Open a shell for command line access.

If you don’t know how to do this, google for "How to open a shell under [your_OS]".
Switch to the javadir directory with the command cd javadir, for example, in the above example via the cd \home\vogella\javastarter command. Use the ls command (dir under Microsoft Windows) to verify that the source file is in the directory.

Compile your Java source file into a class file with the following command.

Afterwards list again the content of the directory with the ls or dir command. The directory contains now a file HelloWorld.class. If you see this file, you have successfully compiled your first Java source code into bytecode.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.
You can now start your compiled Java program. Ensure that you are still in the jardir directory and enter the following command to start your Java program.

java HelloWorld
The system should write "Hello World" on the command line.

Compiling and running Java programs on the command line
3.3. Using the classpath
You can use the classpath to run the program from another place in your directory.

Switch to the command line, e.g., under Windows Start Run cmd. Switch to any directory you want. Type:

java HelloWorld
If you are not in the directory in which the compiled class is stored, then the system will show an error message: Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass

To use the class, type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

java -classpath "mydirectory" HelloWorld

Top comments (0)