AI Hints
Home›Java Tutorial›The main Method, println and print, and Comments
Java · Lesson 7 of 120

The main Method

Where every program starts.

⏱ 2 min read▶ Video at 8:14🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Every Java program has the same outer shape. A class, and inside it, a method called main. Let's read that shape, one piece at a time.

  • The same outer shape
  • A class
  • A main method

Reading line one

Public means other code is allowed to use this. Class means we're making a class, a container for code. Main is its name. And the curly braces hold everything that belongs to it.

keyvalue
publicothers may use it
classa container for code
Mainits name
{ }what belongs inside

Reading line two

Line two starts the main method. A method is a named block of code. Static lets Java call it without creating anything first. Void means it gives nothing back. And String, square brackets, args, can hold extra words from the command line. We'll meet each of these properly, later.

keyvalue
mainwhere the program starts
staticno object needed
voidreturns nothing
String[] argscommand line words

The shape of a program

The class wraps everything. The main method sits inside it. Java always starts at main, and runs its lines in order. Each statement ends with a semicolon. Run it. The two lines print, in order.

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.println("This runs first");
        System.out.println("This runs second");
    }
}
Output
This runs first
This runs second

No main, no start

What if there's no method called main? Here, we named it hello instead. Run it. Java refuses, because it can't find main. Every program needs exactly that name.

Main.javajava
public class Main {
    public static void hello(String[] args) {
        System.out.println("Will this run?");
    }
}
Output
error: can't find main(String[]) method in class: Main

Summary

A program is a class, with a main method inside. Java starts at main, and runs each statement, top to bottom. Next, printing, with println and print.

Key takeaways
  • class Main { }
  • main is the start
  • Statements end with ;
Next up: println and print — show values on screen