Java Syntax
Every language has rules about how sentences are written. In Java these rules are called syntax. The compiler checks them very strictly: one missing bracket or semicolon and the program does not compile. The good news is that there are only a few rules, and you already saw most of them in Get Started.
The shape of every program
public class Main {
public static void main(String[] args) {
System.out.println("Java");
System.out.println("is");
System.out.println("fun");
}
}Java is fun
The program is a class (Main), the class contains a method (main), and the method contains statements. Statements run one after another, from top to bottom.
The main rules
- Statements end with a semicolon.
System.out.println("Java");is one statement. - Curly brackets make blocks. A block groups statements together: the body of a class, of a method, of an
ifor a loop. Every{needs a matching}. - Java is case-sensitive.
Systemandsystemare different names.Mainandmainare different too, which is why the class isMainand the method ismain. - Spaces and new lines are free. Java does not care how you indent, but people do: indent each block by four spaces so the structure is easy to see. The editor does this for you.
- Names of classes start with a capital letter (
Main,Student), names of methods and variables with a small letter (main,totalPrice). This is a convention, not a rule, but every Java programmer follows it.
One statement, many lines
A long statement can be split over several lines; the semicolon marks where it ends:
public class Main {
public static void main(String[] args) {
System.out.println("This is a long sentence that we split "
+ "over two lines with a plus sign.");
}
}This is a long sentence that we split over two lines with a plus sign.
The + joins two pieces of text into one. You will learn more about joining text in the Strings topic.
A mistake on purpose
Here a semicolon is missing. Read what the compiler says:
public class Main {
public static void main(String[] args) {
System.out.println("One")
System.out.println("Two");
}
}Main.java:3: error: ';' expected
The message points at the end of line 3, where Java expected a semicolon. The editor marks that line in red.
Practice exercises
- Print a short poem of four lines, one
printlnfor each line. - Change
Systemtosystemin one line, run the program and read the error. Fix it. - Remove one closing curly bracket and see which line the compiler complains about.