Introduction to Java: First Java Program

Posted by Hayri Cicek on June 07, 2019


In this tutorial we will learn how to write, compile and run our first Java program.
You need to have Java installed on your system, go to https://openjdk.java.net/ and download JDK for the operating system you use.

Open a text editor like Visual Studio Code, NotePad or something else and type in the following:


public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}


public class HelloWorld
Every Java program must have at least one class followed by class name.

public static void main(String[] args) This is the next line in our program and main method is the entry point in any Java program.
public keyword is used to make methods public and public methods can be called from outside of the class.
We don't need to create an object when we use static on methods to be run.
void means that the method does not return anything.
String[] args is used for command line arguments.

Save this file as HelloWorld.java, the filename should be same as the class name within the source code.
In your terminal navigate to the folder where you saved the HelloWorld.java file and type the following:

$ javac HelloWorld.java
javac tool converts the source code into bytecode class files. Now type the following command to execute the program.

$ java HelloWorld
You should se the following output in your terminal.

Hello World.

Congratulations, you wrote your first Java program.


Share this: