
In this article I will demonstrate how to compile your first Java program from the command line. Our first program will not be anything fancy, it will be the defacto standard first program everyone has written at least once, the Hello World program.
This post is assuming you already have a working installation of the Java SDK installed on your workstation, if you do not you can see the instructions for installing the SDK on Ubuntu here.
Write Your Program
As I stated before our first program will be a basic Hello World, so the first thing we need to do is create a file “HelloWorld.java”. Below is an example of creating that file on a Linux system.
1 |
user@workstation:~$ touch HelloWorld.java |
Next edit the file with your favorite text editor such as nano or vi and copy in the following source code.
1 2 3 4 5 6 7 8 |
// Creates our class "HelloWorld" public class HelloWorld { // This is our "main" function public static void main(String args[]) { // Prints our the text "Hello World!" to the terminal (minus the quotes) System.out.println("Hello World!"); } } |
Now save and close the file.
Compile the Code
Unlike languages like Python or Bash we can’t just run that file directly, we first need to compile it down using the Java compiler. To do compile your source code issue the command below in the same directory that your “.java” file is located in.
1 2 |
user@workstation:~$ javac HelloWorld.java user@workstation:~$ |
Now if you list the files in that directory you will also have a HelloWorld.class file
1 2 3 |
user@workstation:~$ ls HelloWorld.class HelloWorld.java user@workstation:~$ |
Run the Code
Now if you issue the following command you will see the output of your program which is “Hello World”
1 2 3 |
user@workstation:~$ java HelloWorld Hello World! user@workstation:~$ |
And that is it, you just wrote, compiled, and ran your first Java program.
The Gotchas
It may seem that you have to run the newly created “HelloWorld.class” file in order to run your program but if you do that you will get an error such as the one below.
1 2 3 4 |
user@workstation:~$ java HelloWorld.class Error: Could not find or load main class HelloWorld.class Caused by: java.lang.ClassNotFoundException: HelloWorld.class user@workstation:~$ |
So make sure that you leave out the “.class” and just issue the command “java HelloWorld” and you will be working alright.
Leave a Reply