Careeroza
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 classOutput
Java syntax
Syntax Rules
- Java is case-sensitive:
Mainandmainare different.Systemmust start with a capital S. - Class names start with a capital letter by convention (
Main,OrderService). - The file name must match the
publicclass name:public class Mainlives inMain.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
| Mistake | Compiler 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 end | reached end of file while parsing |
public class Hello inside Main.java | class Hello is public, should be declared in a file named Hello.java |