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. Apublicclass must be saved in a file with exactly the same name, soCafegoes inCafe.java. - The method.
mainis where the JVM starts. Its header is alwayspublic 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.printlnprints its text and then moves to a new line.System.out.printprints 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.
Systemandsystemare different names, and only the first one exists.Stringis a type;stringis 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.