Skip to the workspace
Pebellslearn by building
Java Basics  ›  Lesson

Basic Syntax: Classes, main and Statements

Basic Syntax 12 minEvery Java statement ends with a semicolon and sits inside a method, every method sits inside a class, and the program starts at main.

java / Basic Syntax: Classes, main and Statements

Explore each scene at your own pace.

01 · The rule

The rule

Basic Syntax: Classes, main and Statements

Every Java statement ends with a semicolon and sits inside a method, every method sits inside a class, and the program starts at main.

Identify the entry method and the boundaries of classes, blocks and statements.

Brew Bar's first program only needs to greet customers. Even that one line of output needs a surrounding structure, because Java is strict about where code may live. Learn the structure once and every Java file you open will look familiar.

The rule

Statements live in methods; methods live in classes.

Here is the whole greeting program, saved as Cafe.java:

public class Cafe {
    public static void main(String[] args) {
        // Greet the first customer of the day
        System.out.println("Welcome to Brew Bar");
        System.out.println("What can we make for you?");
    }
}

Reading from the outside in:

  • The class. public class Cafe { ... } is the container. A public class must be saved in a file with exactly the same name, so Cafe goes in Cafe.java.
  • The method. main is where the JVM starts. Its header is always public static void main(String[] args). You will learn every word of it later; for now, copy it exactly.
  • The statements. Each instruction ends with a semicolon ;. System.out.println prints its text and then moves to a new line. System.out.print prints without the line break.

A few more rules to keep in mind:

  • Braces group code. Every { needs a matching }. Indentation is for humans; the braces are what Java reads.
  • Case matters. System and system are different names, and only the first one exists. String is a type; string is an error.
  • Text goes in double quotes. "Welcome" is a piece of text, called a string.
  • Comments are ignored. // to the end of the line, /* across several lines */, and /** documentation comments */ that tools turn into reference pages.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.