Java Syntax & Structure
Every programming language has rules — a specific grammar it follows. In Java, these rules are called syntax.
Break the syntax and the compiler refuses to run your program. Follow it correctly and you have a working foundation for anything you want to build.
This page covers all the fundamental syntax rules and structural conventions of Java — the things every program follows, every single time.
👉 What you'll learn here:
- ›The structure every Java program follows
- ›Rules for naming classes, variables, and methods
- ›How statements, blocks, and whitespace work
- ›Java's case sensitivity rules
- ›Conventions that make your code readable
🧘 Syntax is learned by writing, not memorizing.
Read through this page to understand the rules. Then as you write your first programs, refer back when something doesn't compile. Within a few weeks, correct Java syntax will feel completely natural.
The Basic Structure of Every Java Program
Every Java program — from the simplest Hello World to a production server — follows this same skeleton:
public class ClassName {
public static void main(String[] args) {
// statements go here
}
}Three nested layers, every time:
- ›Class — the outermost container. Everything lives inside a class.
- ›Method — a named block of code inside the class.
mainis the entry point. - ›Statements — the actual instructions inside the method.
Rule 1 — Java is Case-Sensitive
Java treats uppercase and lowercase letters as completely different. This applies to everything — class names, method names, variable names, and keywords.
// These are all different things to Java:
String name = "Arjun"; // ✅ correct
string name = "Arjun"; // ❌ error — 'string' doesn't exist
String Name = "Arjun"; // different variable from 'name'
// These method calls are all different:
System.out.println("Hello"); // ✅ correct
system.out.println("Hello"); // ❌ error — 'system' doesn't exist
System.out.Println("Hello"); // ❌ error — 'Println' doesn't exist
System.out.printLn("Hello"); // ❌ error — 'printLn' doesn't exist⚠️ Case sensitivity is the #1 cause of beginner compile errors. When your code doesn't compile and you can't see why — check capitalization first.
Rule 2 — Every Statement Ends with a Semicolon
A statement is a single instruction. In Java, every statement ends with a semicolon ;.
System.out.println("Hello"); // ✅ statement with semicolon
int age = 25; // ✅ statement with semicolon
String name = "Arjun"; // ✅ statement with semicolonForget the semicolon and you get a compile error:
System.out.println("Hello") // ❌ error: ';' expected💡 Think of the semicolon as a period at the end of a sentence. Just as English sentences end with a period, Java statements end with a semicolon. It tells the compiler: "this instruction is complete."
What does NOT need a semicolon:
public class HelloWorld { // ← no semicolon — class declaration
public static void main(...) { // ← no semicolon — method declaration
System.out.println("Hi"); // ← semicolon — this is a statement
} // ← no semicolon — closing brace
} // ← no semicolon — closing braceThe rule is: statements get semicolons. Declarations with {} blocks do not.
Rule 3 — Curly Braces Define Blocks
Blocks are sections of code enclosed in curly braces { }. Every class and every method has a block.
public class Example { // opens class block
public static void main(String[] args) { // opens method block
System.out.println("Inside the method block");
} // closes method block
} // closes class blockRules for braces:
- ›Every
{must have a matching} - ›Blocks can be nested — methods inside classes, if-statements inside methods
- ›The content inside a block is indented (not required by Java, but required for readability)
A missing or extra brace is one of the most common compile errors:
public class Example {
public static void main(String[] args) {
System.out.println("Hello");
}
// ← missing closing } for classError: error: reached end of file while parsing
💡 Brace matching tip: Most code editors highlight matching braces when your cursor is on one. In VS Code and IntelliJ, clicking on a { highlights its matching }. Use this constantly when debugging.
Rule 4 — The Class Name Must Match the Filename
In Java, the public class name must exactly match the filename — including capitalization.
File: HelloWorld.java → class must be named HelloWorld
File: BankAccount.java → class must be named BankAccount
File: myclass.java → class must be named myclass
// File: HelloWorld.java
public class HelloWorld { // ✅ names match
...
}
// File: HelloWorld.java
public class helloworld { // ❌ error — 'helloworld' ≠ 'HelloWorld'
...
}Error: class helloworld is public, should be in a file named helloworld.java
Rule 5 — Whitespace is Ignored (Mostly)
Java ignores extra spaces, tabs, and blank lines between tokens. This means you control your code's visual layout freely — the compiler doesn't care.
// These are identical to the compiler:
// Compact:
public class A{public static void main(String[] args){System.out.println("Hi");}}
// Readable:
public class A {
public static void main(String[] args) {
System.out.println("Hi");
}
}Both compile and run identically. But only one is readable.
Exception — whitespace inside Strings:
System.out.println("Hello World"); // prints: Hello World
System.out.println("Hello World"); // prints: Hello World (two spaces)Whitespace inside String literals is preserved exactly.
Naming Rules — What You Can and Cannot Name Things
Java has strict rules for identifiers — the names you give to classes, methods, and variables.
Legal identifier rules:
- ›Can contain letters, digits, underscores
_, and dollar signs$ - ›Must not start with a digit
- ›Must not be a Java keyword (like
class,int,if,return) - ›No spaces allowed
// ✅ Valid identifiers:
int age = 25;
String firstName = "Arjun";
double _salary = 50000.0;
int count1 = 0;
// ❌ Invalid identifiers:
int 1count = 0; // starts with digit
String my name = ""; // contains space
int class = 5; // 'class' is a keyword
double my-salary; // hyphen not allowedNaming Conventions — How Java Developers Actually Name Things
Beyond the legal rules, Java has strong conventions — community-agreed styles that make code readable. The compiler doesn't enforce these, but every Java developer follows them.
Classes — PascalCase
Every word starts with an uppercase letter. No underscores.
public class HelloWorld { }
public class BankAccount { }
public class StudentGradeCalculator { }Variables and Methods — camelCase
First word lowercase, every subsequent word starts uppercase. No underscores.
int age = 25;
String firstName = "Arjun";
double accountBalance = 5000.0;
public void calculateTax() { }
public String getStudentName() { }Constants — UPPER_SNAKE_CASE
All uppercase, words separated by underscores. Used with static final.
static final int MAX_SIZE = 100;
static final double PI = 3.14159;
static final String APP_NAME = "DevStackFlow";Packages — all lowercase
package com.devstackflow.utils;
package org.example.models;Comments — Ignoring Code
Comments are lines the compiler completely ignores. They exist for humans reading the code.
Single-line comment
// This is a single-line comment
int age = 25; // you can also put comments at the end of a lineMulti-line comment
/*
This is a multi-line comment.
It can span as many lines as you need.
The compiler ignores everything between the markers.
*/
int salary = 50000;Javadoc comment
Used to generate documentation automatically from your code:
/**
* Calculates the area of a rectangle.
* @param width the width of the rectangle
* @param height the height of the rectangle
* @return the area as a double
*/
public double calculateArea(double width, double height) {
return width * height;
}💡 When to comment: Don't comment what the code obviously does (// adds 1 to count). Comment why you made a decision, or explain something non-obvious. Good code mostly explains itself through clear naming.
Keywords — Words Reserved by Java
Java has 67 reserved keywords — words with specific meaning that you cannot use as identifiers. Here are the most important ones you'll use regularly:
| Category | Keywords |
|---|---|
| Data types | int, double, boolean, char, long, float, byte, short |
| Class & OOP | class, interface, extends, implements, new, this, super |
| Access | public, private, protected |
| Control flow | if, else, switch, case, for, while, do, break, continue, return |
| Other common | static, final, void, null, true, false, import, package |
// ❌ You cannot use keywords as variable names:
int class = 5; // error — 'class' is a keyword
String return = ""; // error — 'return' is a keyword
boolean true = false; // error — 'true' is a keywordA Complete Example — All Rules Applied
Here's a program that demonstrates every syntax rule covered on this page:
// File: BankAccount.java
public class BankAccount { // PascalCase class name matches filename
// Constant — UPPER_SNAKE_CASE
static final double INTEREST_RATE = 0.05;
// Instance variables — camelCase
String accountHolder;
double balance;
// Method — camelCase, returns void
public void deposit(double amount) {
balance = balance + amount; // statement ends with ;
System.out.println("Deposited: " + amount);
System.out.println("New balance: " + balance);
}
// Entry point
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.accountHolder = "Arjun";
account.balance = 1000.0;
account.deposit(500.0);
System.out.println("Account holder: " + account.accountHolder);
System.out.println("Interest rate: " + INTEREST_RATE);
}
}Output:
Deposited: 500.0
New balance: 1500.0
Account holder: Arjun
Interest rate: 0.05
Every concept from this page is used here — PascalCase class, camelCase methods and variables, UPPER_SNAKE_CASE constant, semicolons on statements, braces on blocks, and comments throughout.
Common Syntax Mistakes — Quick Reference
| Mistake | Example | Fix |
|---|---|---|
| Missing semicolon | System.out.println("Hi") | Add ; at the end |
| Wrong capitalization | system.out.println(...) | Use System.out.println(...) |
| Mismatched braces | public class A { void m() { } | Add closing } for class |
| Filename ≠ class name | File: hello.java, class: Hello | Match exactly: Hello.java |
| Keyword as identifier | int class = 5; | Use a non-keyword name |
| Starting name with digit | int 1count = 0; | Start with a letter: int count1 |
| Space in identifier | String my name; | Remove space: String myName; |
The 3 Things to Remember From This Page
- ›Every statement ends with
;— declarations with{}do not. This single rule eliminates the most common category of compile errors. - ›Java is fully case-sensitive —
System,String,printlnmust be capitalized exactly right. When code won't compile and you can't see why, check capitalization first. - ›Follow naming conventions — PascalCase for classes, camelCase for variables and methods, UPPER_SNAKE_CASE for constants. The compiler doesn't enforce these, but every Java developer follows them.
Summary
- ›Every Java program has three nested layers: class → method → statements
- ›Java is completely case-sensitive —
Stringandstringare different things - ›Every statement ends with a semicolon
;— class and method declarations with{}do not - ›Curly braces
{ }define blocks — every opening{needs a matching closing} - ›The public class name must exactly match the filename including capitalization
- ›Extra whitespace (spaces, blank lines) is ignored by the compiler — use it freely for readability
- ›Identifiers cannot start with a digit, cannot contain spaces, and cannot be Java keywords
- ›Naming conventions: PascalCase for classes, camelCase for variables and methods, UPPER_SNAKE_CASE for constants
- ›Comments (
//and/* */) are ignored by the compiler — use them to explain your code
What to Read Next
See the reserved words Java already has a meaning for.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
The first program every Java developer writes.
Stores a name in a variable and prints it to the console.
Adds two fixed integers and prints the result.