Syntax & Comments

Every language has rules for how code must be written. Java's are strict but consistent: statements end with semicolons, blocks use braces, names are case-sensitive. This lesson covers those rules, naming conventions, and the three kinds of comments.

Statements and blocks

JAVA
void main() {
    int apples = 3;
    int pears = 4;
    if (apples < pears) {
        System.out.println("More pears");
        System.out.println("Total: " + (apples + pears));
    }
}
Output
More pears
Total: 7
  • A statement is one instruction, ending with ;.
  • A block is a group of statements in { }. Methods, classes, if and loops all use blocks.
  • Whitespace and line breaks don't matter to the compiler, but consistent indentation (usually four spaces) matters a great deal to humans.

Case sensitivity

JAVA
void main() {
    int total = 10;
    System.out.println(Total);
}
Compiler error
Main.java:3: error: cannot find symbol

total and Total are different names. "cannot find symbol" is the error you'll see most often as a beginner — it usually means a typo or a variable used outside where it was declared.

Comments

JAVA
/**
 * Prints a short greeting.
 * This is a documentation comment.
 */
void main() {
    // A single-line comment explains the next line
    System.out.println("Hi"); // comments can follow code too

    /* A multi-line comment
       can span several lines. */
    // System.out.println("This line is disabled");
}
Output
Hi
SyntaxUse
// …Short notes and temporarily disabling a line
/* … */Longer explanations
/** … */Javadoc: documentation for classes and methods, turned into HTML by the javadoc tool

Good comments explain why code does something, not what it does — the code itself should be clear about the what.

Identifiers and naming conventions

Names (identifiers) may contain letters, digits, _ and $, but can't start with a digit or be a keyword (class, int, if…). Java code follows strong conventions:

KindConventionExamples
Classes, interfaces, records, enumsPascalCaseCustomer, OrderService
Methods and variablescamelCasetotalPrice, calculateTax()
ConstantsUPPER_SNAKE_CASEMAX_SIZE, TAX_RATE
Packageslowercase, reversed domaincom.example.shop

The compiler doesn't enforce these, but every Java developer expects them. Choose descriptive names: unitPrice rather than up.

Literals

JAVA
void main() {
    System.out.println(1_000_000);   // underscores make long numbers readable
    System.out.println(0xFF);        // hexadecimal
    System.out.println(0b1010);      // binary
    System.out.println('A');         // a single character
    System.out.println(3.14);        // a decimal number
    System.out.println(true);        // a boolean
}
Output
1000000
255
10
A
3.14
true

Try it yourself

Fix the compile errors: there are three.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java