Java Syntax

Structure of a Java Program

Example

Every Java program has at least one class and a main method.

public class Main {                            // class declaration
    public static void main(String[] args) {   // entry point
        System.out.println("Java syntax");      // statement ends with ;
    }                                           // end of main
}                                               // end of class

Output

Java syntax

Syntax Rules

  • Java is case-sensitive: Main and main are different. System must start with a capital S.
  • Class names start with a capital letter by convention (Main, OrderService).
  • The file name must match the public class name: public class Main lives in Main.java.
  • Each statement ends with a semicolon ;.
  • Code blocks are wrapped in curly braces { }.
  • Whitespace and indentation do not change meaning (unlike Python), but they make code readable. Use 4 spaces.

Common Beginner Mistakes

MistakeCompiler message (short)
system.out.println("Hi");package system does not exist
System.out.println("Hi") (no semicolon)';' expected
System.out.println("Hi);unclosed string literal
missing } at the endreached end of file while parsing
public class Hello inside Main.javaclass Hello is public, should be declared in a file named Hello.java