Basic Syntax: Classes, main 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.
The shortcut
Read any Java file like a set of boxes: class box → method box → statements. If a statement sits directly inside a class box, it is in the wrong place.
Find the class box
public class Cafe { ... }inCafe.java. The names match, so the file will compile.
The most common first error is a missing semicolon. javac points at the line after the real problem, so look one line up.
Drills
Answer fast — trust the rule.
A file declares public class BrewBar. What must the file be called?
What is printed by System.out.print("A"); System.out.println("B"); System.out.print("C");?
Why does system.out.println("Hi"); fail to compile?
Where may System.out.println("Open"); be placed?
Remember
- Statements live in methods; methods live in classes; a public class matches its file name.
- Read outside in: class box, method box, statements ending in
;. - Traps: a missing semicolon, and wrong capital letters.
