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.
main MethodAs we saw, the main method is the starting point for any Java program. Its signature is always the same:
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.
{}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.
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
;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.
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 has established conventions for naming classes, methods, and variables to make code more readable.
PascalCase convention (e.g., MyFirstClass, Car, String).camelCase convention (e.g., myMethodName(), calculateSum()).camelCase (e.g., userName, totalScore).Main must be in a file named Main.java).Java is case-sensitive, which means myVariable and MyVariable are treated as two different variables.
What character is used to end a statement in Java?