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
void main() { int apples = 3; int pears = 4; if (apples < pears) { System.out.println("More pears"); System.out.println("Total: " + (apples + pears)); } }
More pears Total: 7
- A statement is one instruction, ending with
;. - A block is a group of statements in
{ }. Methods, classes,ifand 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
void main() { int total = 10; System.out.println(Total); }
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
/** * 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"); }
Hi
| Syntax | Use |
|---|---|
// … | 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:
| Kind | Convention | Examples |
|---|---|---|
| Classes, interfaces, records, enums | PascalCase | Customer, OrderService |
| Methods and variables | camelCase | totalPrice, calculateTax() |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, TAX_RATE |
| Packages | lowercase, reversed domain | com.example.shop |
The compiler doesn't enforce these, but every Java developer expects them. Choose descriptive names: unitPrice rather than up.
Literals
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 }
1000000 255 10 A 3.14 true
Try it yourself
Fix the compile errors: there are three.