JavaJava Syntax

Java Syntax

Java’s syntax belongs to the “C family” of languages — the same lineage as C, C++, C#, and JavaScript. If you’ve worked with any of those before, curly braces, if statements, and semicolons will feel immediately familiar. This page covers the ground rules every Java program follows.

Case Sensitivity

Java is case-sensitive. myVariable, MyVariable, and MYVARIABLE are three completely different identifiers. Class names conventionally start with an uppercase letter (HelloWorld), while variables and methods conventionally start with a lowercase letter (helloWorld) — mixing this up won’t cause a compiler error, but it will confuse other developers (and your future self).

Statements End With a Semicolon

Every statement in Java must end with a semicolon (;). The compiler uses semicolons, not line breaks, to know where one statement ends and the next begins:

Java
int age = 25;
System.out.println(age);
Curly Braces Define Blocks

Curly braces ({ and }) group statements into a block — the body of a class, a method, a loop, or an if statement. Everything inside a matching pair of braces is treated as one unit:

Java
if (age >= 18) {
    System.out.println("You are an adult.");
} else {
    System.out.println("You are a minor.");
}
The Public Class and File Name Must Match

If a .java file contains a public class, that class’s name must exactly match the file name, including capitalization. A file named HelloWorld.java must contain public class HelloWorld, not public class helloworld or public class Hello.

HelloWorld.java — correct

Java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello!");
    }
}
A Very Common Beginner Error
Naming the file `HelloWorld.java` but the class `public class Hello` produces a compiler error along the lines of: **“class Hello is public, should be declared in a file named Hello.java”**. This is one of the most common mistakes for people new to Java — always double-check that your file name and public class name match exactly, character for character.
Execution Starts at main

A runnable Java program needs exactly one entry point: a method with this exact signature:

Java
public static void main(String[] args) {
    // program execution starts here
}
Comments

Java supports single-line comments (// like this) and multi-line comments (/* like this */), both of which the compiler ignores entirely — they exist purely to help human readers.

  • Java is case-sensitive — name and Name are different identifiers.

  • Every statement ends with a semicolon.

  • Curly braces group statements into blocks (classes, methods, loops, conditionals).

  • A public class's name must exactly match its file name.

  • Execution begins in the public static void main(String[] args) method.

Note
Java files can contain more than one class, but at most one of them may be `public`, and if one is, its name is what determines the required file name.