FoundationLesson 1 of 5 in BasicsFree preview

Program Structure

Every Java program lives inside a class. Execution starts at the main method:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  • public: the JVM must be able to call it from outside the class.
  • static: it runs without creating an object of Main.
  • void: it returns nothing.
  • String[] args: command-line arguments.

Every statement ends with ;, and blocks are wrapped in { }.

How it runs: javac Main.java compiles your source into bytecode (Main.class). Then java Main starts the JVM, which runs that bytecode. The same .class file runs on Windows, Linux or Mac. This is the "write once, run anywhere" idea.

The classic trap: a public class must be in a file with the same name. public class Main saved as Hello.java does not compile.

In interviews: "Why is main static?" Because the JVM calls it before any object exists.

Practice

Solve 3 of 4 to complete this lesson.

0/4 solved

Solve 3 more to complete this lesson, or move on and come back later.

Skip to next: Variables and Data Types