Lesson 2 – Java Syntax

Java syntax refers to the rules that define how Java programs are written and understood. Java is strict about punctuation and structure, but once you get used to it, writing programs becomes easy.

1. Every Java Program Starts With a Class

All Java code MUST be inside a class:

public class Main {
}
        

2. The main() Method

The main() method is the starting point of every Java program. Without it, the program will not run.

public static void main(String[] args) {
    System.out.println("Hello Java");
}
        

Breakdown:

3. Printing Output

You use System.out.println() to print text:

System.out.println("Welcome");
System.out.println(5 + 10);
System.out.println("Result: " + 20);
        

More Output Examples

System.out.print("Hello ");
System.out.print("World!");
        

Output: Hello World!

4. Statements End With Semicolons

Every statement in Java must end with a semicolon ;

int x = 10;
System.out.println(x);
        

5. Java Is Case-Sensitive

int age = 20;
int Age = 30;

System.out.println(age);  // 20
System.out.println(Age);  // 30
        

age and Age are different variables.

6. Comments in Java

Single-line Comment:

// This is a comment
System.out.println("Hello");
        

Multi-line Comment:

/*
This is a
multi-line comment
*/
        

7. Curly Braces { } Define Blocks

if (5 > 2) {
    System.out.println("Yes");
}
        

Examples

for (int i = 1; i <= 3; i++) {
    System.out.println("Loop: " + i);
}
        

8. Indentation (Spacing)

Java does not require indentation to run the code, but indentation makes programs readable.

// Good indentation
if (x == 10) {
    System.out.println("Correct");
}

// Bad indentation (still works, but messy)
if (x == 10){System.out.println("Correct");}
        

9. Putting Everything Together

public class Main {
    public static void main(String[] args) {

        // Print a welcome message
        System.out.println("Java Syntax Example");

        int a = 5;
        int b = 10;

        System.out.println("Sum = " + (a + b));
    }
}
        

10. More Simple Examples

// Example 1: Print your name
System.out.println("Khalid");

// Example 2: Print a number
System.out.println(123);

// Example 3: Print text + number
System.out.println("Age: " + 38);

// Example 4: Declare two numbers and print them
int x = 7;
int y = 9;
System.out.println(x + y);

// Example 5: Simple message
System.out.println("Java is fun!");
        
Back to Top