Your First Java Program

In the previous tutorial you learned how to install Java on your computer. Now, let's write a simple Java program.

The following program displays Hello, World! on the screen.

public class Main {

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

Output

Hello World!

Note: A Hello World! program includes the basic syntax of a programming language and helps beginners understand the structure before getting started. That's why it is a common practice to introduce a new language using a Hello World! program.

It's okay if you don’t understand how the program works right now. We will learn about it in upcoming tutorials. For now, just write the exact program and run it.


Working of Java Program

Congratulations on writing your first Java program. Now, let's see how the program works.

public class Main { 

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

Notice the following line of code:

System.out.println("Hello, World!");

In the above code, the System.out.println() statement prints the text Hello, World! to the screen.

Remember these important things about printf:

  • Everything you want to print should be kept inside parentheses ().
  • The text to be printed is enclosed within double quotes "".
  • Each System.out.println() statement ends with a semicolon ;.

Not following the above rules will result in errors and your code will not run successfully.


Basic Structure of a Java Program

As we have seen from the last example, a Java program requires a lot of lines even for a simple program.

For now, just remember every Java program we write will follow this structure.

class Main {
    public static void main(String[] args) {

        ...

    }
}

We will write our code in place of ... inside curly braces.

Next, we will be learning about Java comments.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges