Java 10 – Compile First Java Program

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.

Next edit the file with your favorite text editor such as nano or vi and copy in the following source code.

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.

Now if you list the files in that directory you will also have a HelloWorld.class file

 

Run the Code

Now if you issue the following command you will see the output of your program which is “Hello World”

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.

So make sure that you leave out the “.class” and just issue the command “java HelloWorld” and you will be working alright.

 

Thats all there is to creating your first program, obviously it can get much more complex and advanced but on a basic level it is really that simple.

I hope this was able to help you and if it did please share on social media!

Be the first to comment

Leave a Reply

Your email address will not be published.


*