Java Learner logo
← Exit to Module 1: Getting Started with Java lessons
Module progress · 0%Lesson · 20 min

Module 1: Getting Started with Java

Lesson focus

Your First Java Program: A Line-by-Line Walkthrough

Deconstruct the classic "Hello, World!" program to understand the fundamental syntax of a Java application, including classes, the main method, and printing to the console.

The Anatomy of a Java Program: Let's break down the simplest Java program line by line to understand its core components.

public class Main { ... }: This line declares a class named Main. In Java, all code must reside inside a class. A class is a blueprint for creating objects. The public keyword is an access modifier, meaning this class can be accessed from anywhere in your project. The file name must match the public class name (e.g., Main.java).

public static void main(String[] args) { ... }: This is the main method, the entry point of any Java application. When you run your program, the JVM looks for this exact method signature.

  • public: Again, an access modifier. The JVM needs to be able to call this method from outside the class.
  • static: This keyword means the method belongs to the Main class itself, not to an instance (object) of the class. This allows the JVM to run the method without creating an object first.
  • void: This is the return type. void means that this method does not return any value.
  • main: This is the name of the method.
  • (String[] args): These are the parameters. This specific parameter is an array of strings that allows you to pass command-line arguments to your program.

System.out.println("Hello, World!");: This line does the work of printing text to the console.

  • System: A built-in final class in the java.lang package that contains useful fields and methods for standard input, output, and error streams.
  • out: A static member of the System class. It is an instance of PrintStream, which is a class that has methods for printing output.
  • println(): A method of the out object. It prints the text you provide in the parentheses to the console, and then adds a new line at the end.

Comments in Java: Comments are notes for human readers that are ignored by the compiler.

  • // This is a single-line comment.
  • / This is a multi-line comment. It can span several lines. /

Mini-Exercise: Modify your Main.java file. Change the text inside println() to print your name. Compile and run the program again to see the new output.

public class HelloWorld {
    // This is the main method, the entry point of the program.
    public static void main(String[] args) {
        // This line prints the text "Hello, World!" to the console.
        System.out.println("Hello, World!");
    }
}

Lesson quiz

Which of these is the correct and complete signature for the main method that serves as the entry point for a Java application?

Next lesson →