Java Syntax โ The Complete Guide
Master the fundamental rules and structure of Java code โ from class declarations and statements to identifiers, keywords, whitespace rules, and the anatomy of every Java program.
Last Updated
March 2026
Read Time
16 min
Level
Beginner
Chapter
2 of 35
What is Java Syntax?
Java syntax is the set of rules that defines how Java programs are written and interpreted by the compiler. Just as English has grammar rules (subject, verb, object), Java has syntax rules that every valid Java program must follow โ without exception.
Unlike Python which uses indentation to define code blocks, or JavaScript which is loosely typed, Java has strict, unambiguous syntax rules. The compiler (javac) rejects any program that violates these rules before execution ever happens. This strictness is a feature โ it catches bugs at compile time, not at runtime in production.
Anatomy of a Java Program
Every valid Java program must follow a precise structural hierarchy. Understanding this hierarchy is the single most important foundation for writing Java. The annotated code below shows every component of a real Java program:
// File: StudentGreeter.java
package com.techsustainify.tutorial;
public class StudentGreeter {
// Entry point โ JVM starts here
public static void main(String[] args) {
String name = "Arjun";
int batch = 2026;
System.out.println("Hello, " + name + "! Batch: " + batch);
}
}Output
Hello, Arjun! Batch: 2026The 5 structural layers of every Java program
Statements, Expressions & Blocks
Java code is built from three fundamental building blocks that you must understand before writing any program:
Statements
A statement is a complete unit of execution โ like a sentence in English. Every statement in Java must end with a semicolon (;). Missing a semicolon is one of the most common beginner errors.
// Declaration statement
int score = 95;
// Assignment statement
score = score + 5;
// Method call statement
System.out.println("Score: " + score);
// Control flow statement (no semicolon โ has a block)
if (score >= 90) {
System.out.println("Grade: A");
}Expressions
An expression is any combination of values, variables, operators, and method calls that evaluates to a single value. Expressions form the core of statements.
int a = 10, b = 3;
// Arithmetic expression โ evaluates to 13
int sum = a + b;
// Relational expression โ evaluates to true (boolean)
boolean isPassed = sum > 10;
// String concatenation expression โ "Result: 13"
String msg = "Result: " + sum;
// Method call expression โ returns int
int maxVal = Math.max(a, b);Blocks
A block is a group of statements enclosed in curly braces { }. Blocks define scope โ variables declared inside a block are only accessible within that block.
public class Blocks { // class block โ outermost
public static void main(String[] args) { // method block
int x = 100;
if (x > 50) { // if-block
int bonus = 10; // only visible inside this block
System.out.println(x + bonus);
}
// System.out.println(bonus); โ ERROR: bonus out of scope
}
}Java Keywords โ Reserved Words
Keywords are reserved words with special meaning in Java. They are part of the language specification and cannot be used as identifiers (variable names, method names, class names). Java has 67 reserved keywords as of Java 21.
Identifiers & Naming Rules
An identifier is the name you give to any Java element โ classes, methods, variables, packages, constants. Java has strict rules for what constitutes a valid identifier.
Legal identifier rules
// โ
Valid identifiers
int age;
int _count;
int $price;
int studentAge2026;
int MAX_SIZE;
// โ Invalid identifiers โ compiler error
// int 2name; โ cannot start with digit
// int my-score; โ hyphen not allowed
// int class; โ reserved keyword
// int my score; โ space not allowed
// int @email; โ @ not allowedComments in Java
Comments are ignored completely by the Java compiler. They exist for human readers โ explaining intent, documenting APIs, and annotating complex logic. Java supports three types of comments:
// 1. Single-line comment โ from // to end of line
int speed = 120; // speed in km/h
/*
* 2. Multi-line comment โ spans multiple lines
* Useful for temporarily disabling code blocks
* or writing long explanations
*/
int distance = 500;
/**
* 3. Javadoc comment โ used by javadoc tool to generate HTML docs
*
* Calculates time for a journey.
*
* @param distance total distance in kilometres
* @param speed average speed in km/h
* @return time in hours as a double
* @since Java 1.0
*/
public static double calculateTime(int distance, int speed) {
return (double) distance / speed;
}Whitespace & Indentation in Java
Java is not whitespace-sensitive like Python. The compiler ignores extra spaces, tabs, and blank lines between tokens. However, at least one whitespace character is required to separate keywords and identifiers from each other.
// All three are identical to the compiler:
// Version 1 โ standard 4-space indentation (recommended)
public class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}
// Version 2 โ everything on one line (valid but unreadable)
public class Hello{public static void main(String[] args){System.out.println("Hello");}}
// Version 3 โ extra blank lines (valid)
public class Hello {
public static void main( String[] args ) {
System.out.println( "Hello" ) ;
}
}Java is Case-Sensitive
Java is fully case-sensitive. Every letter's case matters โ in class names, method names, variable names, and keywords. This is one of the most common sources of beginner errors.
// โ
Correct โ System with capital S
System.out.println("Hello");
// โ Error โ system with lowercase s
// system.out.println("Hello"); โ cannot find symbol
// These are THREE different variables:
int age = 25;
int Age = 30;
int AGE = 35;
// Keywords must be lowercase โ these are invalid as keywords:
// Int, INT, For, WHILE โ these become identifiers, not keywords
// int Int = 10; โ valid! 'Int' is an identifier here, not a keywordJava Naming Conventions
Naming rules define what is legal. Naming conventions define what is standard. These conventions are universally followed in Java codebases worldwide. Violating them won't cause a compile error, but it will make your code stand out as unprofessional.
package com.techsustainify.tutorial; // package: all lowercase
public class BankAccount { // class: PascalCase
private static final int MAX_OVERDRAFT = 5000; // constant: UPPER_SNAKE
private String accountHolder; // variable: camelCase
private double currentBalance;
public void depositAmount(double amount) { // method: camelCase
currentBalance += amount;
}
public double getCurrentBalance() {
return currentBalance;
}
}Common Syntax Errors
Every beginner encounters these. Study them now so you can recognize and fix them instantly in your own code:
public class SyntaxErrors {
public static void main(String[] args) {
// ERROR 1: Missing semicolon
// int x = 10 โ 'expected ;'
int x = 10; // โ
fixed
// ERROR 2: Wrong capitalization (Java is case-sensitive)
// system.out.println("Hi"); โ 'cannot find symbol'
System.out.println("Hi"); // โ
fixed
// ERROR 3: Unclosed string literal
// String msg = "Hello; โ 'unclosed string literal'
String msg = "Hello"; // โ
fixed
// ERROR 4: Mismatched braces
if (x > 5) {
System.out.println("big");
} // โ
every { must have a matching }
// ERROR 5: Class name โ filename
// class MyClass {} in file OtherName.java โ compile error
}
}Java 21 Modern Syntax Features
Java 21 LTS (2023) introduced several syntax improvements that make code more concise and expressive. These features are fully available and production-ready in all Java 21+ projects in 2026:
Text Blocks (Java 15+)
// Old way โ messy string concatenation
String oldJson = "{\"name\": \"Arjun\", \"batch\": 2026}";
// Java 15+ Text Block โ clean and readable
String json = """
{
"name": "Arjun",
"batch": 2026,
"language": "Java"
}
""";Records (Java 16+)
// Record โ immutable data class with 1 line of syntax
// Compiler auto-generates: constructor, getters, equals(), hashCode(), toString()
record Student(String name, int rollNo, double gpa) {}
public static void main(String[] args) {
Student s = new Student("Priya", 42, 9.1);
System.out.println(s.name()); // Priya
System.out.println(s); // Student[name=Priya, rollNo=42, gpa=9.1]
}var โ Local Variable Type Inference (Java 10+)
// Before Java 10 โ explicit types everywhere
ArrayList<String> names = new ArrayList<String>();
// Java 10+ โ compiler infers the type from right-hand side
var names = new ArrayList<String>(); // still strongly typed!
var count = 42; // inferred as int
var message = "Hello Java 21"; // inferred as String
// var is NOT dynamic typing โ type is fixed at compile time
// message = 99; โ COMPILE ERROR โ String โ intPattern Matching for instanceof (Java 16+)
Object obj = "Hello, Java 21!";
// Old way โ explicit cast required
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
// Java 16+ pattern matching โ bind variable in one step
if (obj instanceof String s) {
System.out.println(s.length()); // s is already cast and scoped
}Sealed Classes (Java 17+)
// Sealed class โ restricts which classes can extend it
public sealed class Shape permits Circle, Rectangle, Triangle {}
public final class Circle extends Shape { double radius; }
public final class Rectangle extends Shape { double width, height; }
public final class Triangle extends Shape { double base, height; }
// The compiler now knows every possible Shape subtype โ enables exhaustive pattern matchingInterview Questions โ Java Syntax
These are the most commonly asked Java Syntax interview questions for freshers and beginner-level positions. Master these before any Java interview.
Practice Questions โ Test Your Knowledge
Test your understanding of Java Syntax with these practice questions. Try to answer each before revealing โ active recall is the most effective way to learn.
1. What will happen if you write int Class = 10; in Java?
Medium2. How many public classes can exist in a single .java file?
Easy3. What is the output of: System.out.println("Java" + 1 + 2) and System.out.println(1 + 2 + "Java")?
Medium4. Rewrite this code using a Java 16+ record: class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } }
Easy5. What is wrong with this identifier: int my-variable = 5;
Easy6. Explain why var cannot be used as a method parameter type.
HardConclusion โ Java Syntax Mastered
Java syntax is the foundation of everything you will ever write in Java. The rules you have learned in this chapter โ class structure, statements, expressions, blocks, keywords, identifiers, naming conventions, and comments โ apply to every single Java program from a Hello World to a Netflix-scale microservice.
The key takeaways: Java is case-sensitive, every statement ends with a semicolon, the public class name must match the filename, and keywords are reserved and cannot be reused. Follow naming conventions religiously โ they are the mark of a professional Java developer.
Your next step is Java Variables and Data Types โ where you will learn about the 8 primitive types, type casting, and the String class in depth.