Labs ICT
โญ Pro Login

Basic Syntax

Now we get into the nitty gritty. Java syntax is the set of rules that tells Java how to understand your code. Get these rules right and Java will love you. Get them wrong and you will see some very colorful error messages.

Everything is Inside a Class

In Java, all code must live inside a class. Unlike Python where you can just write code at the top level, Java insists on structure. Every file has a class, and the filename must match the class name.

public class MyProgram {
  public static void main(String[] args) {
    System.out.println("Java loves classes");
  }
}

The main Method

Every Java program needs a main method. That is where the JVM starts executing your code. Here is the exact signature you need:

public static void main(String[] args)

Let me break it down:

  • public โ€” the JVM needs to access this method from outside the class
  • static โ€” the JVM calls this without creating an object first
  • void โ€” this method does not return anything
  • String[] args โ€” any command-line arguments you pass get stored here

Statements and Semicolons

Here is a rule you will love to hate. Every statement in Java must end with a semicolon. Forget one and the compiler will refuse to compile your code.

public class Main {
  public static void main(String[] args) {
    int number = 42;
    System.out.println("The answer is " + number);
  }
}

See those semicolons at the end of lines 4 and 5? They tell Java "this statement ends here." Miss one and you get a compilation error. It is annoying at first, but after a few hours you will add them automatically without thinking.

Case Sensitivity

Java is case sensitive. main is not the same as Main. System is not the same as system. If you write system.out.println, Java will look at you like you have three heads.

This is one of the most common mistakes beginners make. You write public static void Main with a capital M and wonder why nothing works. Java tells you exactly what is wrong though โ€” read the error messages carefully. They are surprisingly helpful once you get used to them.

Curly Braces

Java uses curly braces {} to group blocks of code. The opening brace { starts a block, and the closing brace } ends it. Everything inside the braces belongs to that class or method.

Indentation is optional in Java โ€” the compiler does not care. But please, for the love of all that is holy, indent your code. Your future self and anyone else who reads your code will thank you.

๐Ÿงช Quick Quiz

What is the entry point of a Java program?