First Java Program : Hello World

"Hello, World!" program in Java along with a detailed explanation of the code:

HelloWorld.java:

public class HelloWorld {
    public static void main(String[] args) {
        // This is a comment. Comments are ignored by the compiler.
        // The next line prints "Hello, World!" to the console.
        System.out.println("Hello, World!");
    }
}

Explanation:

  • public class HelloWorld {: In Java, every application begins with a class definition. In this case, we define a class named HelloWorld.

  • public static void main(String[] args) {: This line defines the main method, which is the entry point of every Java application. When you run a Java program, it starts executing from the main method.

  • // This is a comment.: Comments in Java start with //. Comments are ignored by the compiler and are used for providing explanations within the code.

  • System.out.println("Hello, World!");: This line prints "Hello, World!" to the console. Let's break it down:

    • System.out: System is a pre-defined class in Java that provides access to the system, and out is an object of type PrintStream which is connected to the console.

    • println("Hello, World!");: println is a method of the PrintStream class used to print a line of text to the console. In this case, it prints "Hello, World!" followed by a new line.

When you run this Java program, it will output:

Hello, World!

Explanation of Execution:

  1. The program starts executing from the main method.

  2. The System.out.println("Hello, World!"); statement is executed, printing "Hello, World!" to the console.

  3. The program completes its execution, and the output is displayed.

This simple program demonstrates the basic structure of a Java application, including class definition, the main method, comments, and the System.out.println statement used for output.

Last updated