Java Syntax

Java Syntax Fundamentals

In the previous chapter, we created our first Java program. Now, let's break down the fundamental syntax rules that you must follow when writing Java code. Understanding these rules is essential for writing code that the compiler can understand and execute.


The main Method

As we saw, the main method is the starting point for any Java program. Its signature is always the same:

The Main Method

public class Main {
  public static void main(String[] args) {
    // Your code goes here
    System.out.println("The main method is where execution begins.");
  }
}

Every Java program must have a main method inside a class.


Code Blocks and Curly Braces {}

In Java, a block of code is a group of zero or more statements that are enclosed in curly braces {}. These blocks define the scope of classes, methods, and control flow statements.

Code Blocks

public class MyClass { // Start of class block

public static void main(String[] args) { // Start of method block int x = 10; if (x > 5) { // Start of if-statement block System.out.println("x is greater than 5"); } // End of if-statement block } // End of method block

} // End of class block


Statements and Semicolons ;

A statement is a single instruction that the Java compiler can execute. Every statement in Java must end with a semicolon ;. The semicolon tells the compiler that the statement is complete.

Forgetting a semicolon is one of the most common errors for beginners.

Semicolon Example

public class SemicolonExample {
  public static void main(String[] args) {
    // This is one statement
    System.out.println("Hello!");
    // This is another statement
    int myNumber = 100;
    // This is a third statement
    myNumber = myNumber + 50;
    System.out.println(myNumber);
  }
}

Java Naming Conventions

Java has established conventions for naming classes, methods, and variables to make code more readable.

Java is case-sensitive, which means myVariable and MyVariable are treated as two different variables.


Exercise

?

What character is used to end a statement in Java?