Java Syntax

Learn Java syntax step by step with simple explanations, examples, and beginner friendly programs.

What is Java Syntax?

Java syntax is a set of rules that defines how Java programs should be written and structured.

Every Java program must follow proper syntax rules, otherwise the compiler will generate errors.

Basic Structure of Java Program

A simple Java program looks like this:

public class Main {

    public static void main(String[] args) {

        System.out.println("Hello Java");

    }

}

Let us understand each part of this program.

Class Declaration

public class Main

Every Java program must contain at least one class.

Main Method

public static void main(String[] args)

The main() method is the starting point of every Java application.

Printing Output

Java uses System.out.println() to print output on the screen.

System.out.println("Welcome to Java");

Output

Welcome to Java

Semicolon in Java

Every statement in Java must end with a semicolon (;).

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

Missing semicolon causes compilation error.

Java is Case Sensitive

Java treats uppercase and lowercase letters differently.

System.out.println("Correct");

system.out.println("Wrong");

In Java:

Comments in Java

Comments are used to explain code. Comments are ignored by the compiler.

Single Line Comment

// This is single line comment

Multi Line Comment

/*
This is
multi line comment
*/

Variables in Java

Variables are used to store data.

int age = 25;

String name = "John";

double salary = 45000.50;

Rules for Variable Names

Curly Braces { }

Curly braces define blocks of code in Java.

if(true) {

    System.out.println("Java");

}

Indentation

Indentation improves readability of code. Although Java compiler ignores spaces, proper indentation makes code easier to understand.

public class Test {

    public static void main(String[] args) {

        System.out.println("Good Formatting");

    }

}

Java Keywords

Keywords are reserved words in Java. They have predefined meanings.

  • class
  • public
  • static
  • void
  • int
  • double
  • if
  • else
  • for

Complete Java Example

public class Student {

    public static void main(String[] args) {

        String name = "Alex";

        int age = 20;

        System.out.println(name);

        System.out.println(age);

    }

}

Output

Alex
20

Common Syntax Errors

Conclusion

Understanding Java syntax is the first step toward becoming a Java developer. Once you learn syntax properly, writing Java programs becomes much easier.