How To Write First Java Program

First Program

By Mayuri Fakirpure

Updated on Feb 09, 2024

In this chapter, we will explain how to write first Java program. We will write Hello World! simple program. It make sure that our environment set correctly.

Writing Hello World! program is recommended at starting our programmer journey, because it will help us to check if there is error in our environment set. It is simple and knowledgable program.

Prerequisites

  • Linux based system.
  • Installed Java Development Kit(JDK). If you haven't already installed it, you can follow our JDK installation process. 
  • Basic Java programming knowledge.
  • Basic Linux knowledge.

Write Your Java Code

Open your preferred text editor or IDE and create a file name with the .java extension. 

nano HelloWorld.java

Remember: You need to create file with the public class name which contains main function. If you do not do that you will get error. Here we are creating class name HelloWorld so that, we have set file name HelloWorld.

Here is a simple Hello, World! program. Copy and paste following content in your file:

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

Save and exit. 

Compile Your Java Code

In terminal, navigate to the directory where your .java file is located. Now, lets compile it with javac command. Execute following command:

javac HelloWorld.java

If we do not get any syntax error, this command will generate a bytecode file named HelloWorld.class, which contains the compiled Java code.

Run Your Java Program

Once we compile our program, lets run it using java command followed by the name of the class that contains the main method(without the .class extension):

java HelloWorld

If everything is set upd correctly, it will print  Hello, World!.

That's it! We have written and executed our first Java program. Explore our topics related to Java programming. You will find some amazing topics.

We have seen how to write first Java program. This chapter is completed.