Java Syntax
Java syntax is the set of rules for writing Java code so the compiler can understand it. A Java program is built from classes, methods, statements, and punctuation such as braces and semicolons.
This lesson explains the basic shape of a Java program and the small details that must be written exactly.
Basic Java Program Structure
Most beginner Java examples in this course use a class named Main. Inside that class is the main method, which is where the program starts running.
public class Main {
public static void main(String[] args) {
System.out.println("Java syntax matters.");
System.out.println("Each statement ends with a semicolon.");
}
}
Output:
Java syntax matters.
Each statement ends with a semicolon.
How The Syntax Works
The line public class Main creates a class named Main. In Java, code belongs inside a class. If a class is declared as public, the source file should have the same name as the class, such as Main.java.
The line public static void main(String[] args) declares the main method. Java begins running the program from this method. For now, you do not need to memorize every word in the method header, but you should type it carefully.
The statements inside the method are executed from top to bottom. In the example, the first System.out.println() statement runs before the second one.
Braces Group Code
Curly braces { and } mark the beginning and end of a block of code. The class has its own pair of braces, and the main method has another pair inside it.
Indentation is not required by the compiler, but it makes the structure easier to read. Code inside a block is normally indented by four spaces.
Statements And Semicolons
A statement is an instruction that tells Java to do something. Many Java statements end with a semicolon ;.
For example, System.out.println("Hello"); is a statement. If you leave off the semicolon, the compiler will report an error.
Text Uses Double Quotes
Text values in Java are called strings. A string is written between double quotes, like "Java". The text inside the quotes is printed exactly as written.
Single quotes are used for single characters, not normal text. For beginner output, use double quotes with System.out.println().
Java Is Case-Sensitive
Java treats uppercase and lowercase letters as different. The name Main is not the same as main, and System is not the same as system.
public class Mainuses an uppercaseM.mainin the method name uses a lowercasem.System.out.printlnuses an uppercaseSinSystem.
Common Syntax Rules
- Java code is written inside classes.
- The
mainmethod is the starting point of a Java program. - Blocks of code are surrounded by
{and}. - Most statements end with
;. - Strings are written inside double quotes.
- Names must use the correct uppercase and lowercase letters.
Takeaway: Java syntax is strict, but predictable; once you recognize classes, methods, braces, statements, and semicolons, Java programs become much easier to read.
