Java Syntax

Java syntax is the set of rules that decides how a Java program must be written. Once you understand the structure of one small program, you will recognise the same shape in every Java file you see.

The Structure of a Java Program

public class Greeter {
    public static void main(String[] args) {
        System.out.println("Line one");
        System.out.println("Line two");
    }
}
Line one
Line two
  • public class Greeter declares a class. Every piece of Java code lives inside a class.
  • The file must be named Greeter.java because the class is public.
  • public static void main(String[] args) is the main method, where the program starts.
  • public means it can be called from outside, static means no object is needed, void means it returns nothing.
  • String[] args holds any command-line arguments passed to the program.
  • Each statement ends with a semicolon.
  • Curly braces { } mark the start and end of blocks of code.

Java Is Case Sensitive

Java treats uppercase and lowercase letters as different. System must start with a capital S, and a variable called total is not the same as Total. Writing system.out.println will not compile.

Naming Conventions

  • Classes use PascalCase: Main, BankAccount, OrderService.
  • Methods and variables use camelCase: printTotal, firstName.
  • Constants use UPPER_SNAKE_CASE: MAX_SIZE.
  • Packages use lowercase: com.example.shop.

Statements and Blocks

A statement is one instruction. A block groups statements between braces. Whitespace and indentation do not change the meaning in Java, but consistent indentation (usually four spaces) makes code much easier to read.

public class Main {
    public static void main(String[] args) {
        int apples = 4;
        int oranges = 6;
        int fruit = apples + oranges;
        System.out.println("Total fruit: " + fruit);
    }
}
Total fruit: 10

Here three statements declare variables and do arithmetic, and the last prints the result. The + operator joins the text and the number into one string.

Frequently asked questions

Why does Java need a main method?

The JVM needs a known starting point. When you run a class, it looks for public static void main(String[] args) and starts executing there.

Do I need a semicolon after every line in Java?

Every statement needs a semicolon, but lines that open or close blocks, like class and method declarations or closing braces, do not.

Can a Java file contain more than one class?

Yes, but only one top-level class can be public, and the file name must match that public class.