Java Syntax
Java Syntax (Beginner-Friendly Guide)
Once Java is installed and ready, the next step is understanding the syntax β the rules for writing Java code correctly.
β Basic Java Program Structure
Breakdown:
| Part | Meaning |
|---|---|
class Main |
Defines a class named Main |
{ } |
Curly braces define the body of the class or method |
public static void main(String[] args) |
Entry point of every Java program |
System.out.println() |
Prints output to the console |
π§© Java is Case Sensitive
Examples:
| Correct | Incorrect |
|---|---|
System.out.println() |
system.out.println() |
main |
Main (wonβt run) |
class |
Class |
π Statements and Semicolons
Every executable statement ends with a semicolon (;).
Example:
π Comments in Java
Comments are ignored by the compiler.
1οΈβ£ Single-line Comment
2οΈβ£ Multi-line Comment
3οΈβ£ Documentation Comment (For APIs)
π Java Naming Rules
| Rule | Example |
|---|---|
| Class name starts with Capital letter | class Student { } |
| Method and variable names start with lowercase | int age; void display() |
| CamelCase convention | studentName, totalAmount |
1 2 3 4 5 6 7 8 9 |
Invalid: β int 1count; β class public; (keyword not allowed) Valid: β int count1; β int _value; |
π Java Print Statements
Output:
π Variables and Data Types Example
π Syntax Errors vs. Runtime Errors
| Type | Meaning | Example |
|---|---|---|
| Syntax Error | Code written incorrectly | Missing semicolon |
| Runtime Error | Error while program runs | Divide by zero |
| Logic Error | Wrong output | Incorrect formula |
π Example Program with Variables & Comments
π― Key Points to Remember
-
Java code must be inside a class.
-
Program execution always starts from
main()method. -
Statements end with
; -
Java uses {} to group code blocks.
-
Follow camelCase naming rules.
