Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

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");
    }
}
Output
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 if or a loop. Every { needs a matching }.
  • Java is case-sensitive. System and system are different names. Main and main are different too, which is why the class is Main and the method is main.
  • 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.");
    }
}
Output
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");
    }
}
The compiler says
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

  1. Print a short poem of four lines, one println for each line.
  2. Change System to system in one line, run the program and read the error. Fix it.
  3. Remove one closing curly bracket and see which line the compiler complains about.