Java Syntax
Java syntax defines the required structure of a program: classes, the main method, statements, and blocks.
The structure of a Java program
Every Java program is built from classes, and every statement lives inside a method that lives inside a class. When you run a program, Java looks for a special method called main and starts there. Understanding this skeleton makes every later lesson easier.
The basic skeleton
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Breaking down the pieces
- public class Main declares a class named Main; the file must be saved as Main.java
- public static void main(String[] args) is the entry point where execution begins
- System.out.println(...) prints a line of text to the console
- Curly braces { } group the code that belongs together into a block
- The semicolon ; marks the end of each statement
Statements and blocks
A statement is a single instruction, and in Java it almost always ends with a semicolon. A block is a group of statements wrapped in curly braces. Blocks define where a class or method begins and ends, and they can be nested inside one another.
Whitespace and indentation
Java ignores extra spaces and blank lines, so indentation does not change how a program behaves. However, consistent indentation makes code far easier to read, and by convention each nested block is indented one level deeper than its parent.
Multiple statements in main
public class Main {
public static void main(String[] args) {
System.out.println("Line one");
System.out.println("Line two");
System.out.println("Line three");
}
}Exercise: Java Syntax
What must end most executable statements in Java?