Java Tutorial
🔍

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:

Java
1public class ClassName { 2 3 public static void main(String[] args) { 4 // statements go here 5 } 6 7}

Three nested layers, every time:

  • Class — the outermost container. Everything lives inside a class.
  • Method — a named block of code inside the class. main is the entry point.
  • Statements — the actual instructions inside the method.
JAVA PROGRAM STRUCTURE CLASS — Container for all code public class MyProgram { ... } METHOD — Named block of code public static void main(String[] args) { ... } STATEMENTS — Individual instructions System.out.println("Hello"); // ends with ; } ← closes method } ← closes class

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.

Java
1// These are all different things to Java: 2String name = "Arjun"; // ✅ correct 3string name = "Arjun"; // ❌ error — 'string' doesn't exist 4String Name = "Arjun"; // different variable from 'name' 5 6// These method calls are all different: 7System.out.println("Hello"); // ✅ correct 8system.out.println("Hello"); // ❌ error — 'system' doesn't exist 9System.out.Println("Hello"); // ❌ error — 'Println' doesn't exist 10System.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 ;.

Java
1System.out.println("Hello"); // ✅ statement with semicolon 2int age = 25; // ✅ statement with semicolon 3String name = "Arjun"; // ✅ statement with semicolon

Forget the semicolon and you get a compile error:

Java
1System.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:

Java
1public class HelloWorld { // ← no semicolon — class declaration 2 public static void main(...) { // ← no semicolon — method declaration 3 System.out.println("Hi"); // ← semicolon — this is a statement 4 } // ← no semicolon — closing brace 5} // ← no semicolon — closing brace

The 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.

Java
1public class Example { // opens class block 2 public static void main(String[] args) { // opens method block 3 System.out.println("Inside the method block"); 4 } // closes method block 5} // closes class block

Rules 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:

Java
1public class Example { 2 public static void main(String[] args) { 3 System.out.println("Hello"); 4 } 5// ← missing closing } for class

Error: 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
Java
1// File: HelloWorld.java 2public class HelloWorld { // ✅ names match 3 ... 4} 5 6// File: HelloWorld.java 7public class helloworld { // ❌ error — 'helloworld' ≠ 'HelloWorld' 8 ... 9}

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.

Java
1// These are identical to the compiler: 2 3// Compact: 4public class A{public static void main(String[] args){System.out.println("Hi");}} 5 6// Readable: 7public class A { 8 public static void main(String[] args) { 9 System.out.println("Hi"); 10 } 11}

Both compile and run identically. But only one is readable.

Exception — whitespace inside Strings:

Java
1System.out.println("Hello World"); // prints: Hello World 2System.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
Java
1// ✅ Valid identifiers: 2int age = 25; 3String firstName = "Arjun"; 4double _salary = 50000.0; 5int count1 = 0; 6 7// ❌ Invalid identifiers: 8int 1count = 0; // starts with digit 9String my name = ""; // contains space 10int class = 5; // 'class' is a keyword 11double my-salary; // hyphen not allowed

Naming 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.

Java
1public class HelloWorld { } 2public class BankAccount { } 3public class StudentGradeCalculator { }

Variables and Methods — camelCase

First word lowercase, every subsequent word starts uppercase. No underscores.

Java
1int age = 25; 2String firstName = "Arjun"; 3double accountBalance = 5000.0; 4 5public void calculateTax() { } 6public String getStudentName() { }

Constants — UPPER_SNAKE_CASE

All uppercase, words separated by underscores. Used with static final.

Java
1static final int MAX_SIZE = 100; 2static final double PI = 3.14159; 3static final String APP_NAME = "DevStackFlow";

Packages — all lowercase

Java
1package com.devstackflow.utils; 2package org.example.models;
JAVA NAMING CONVENTIONS Classes → PascalCase BankAccount StudentGradeCalculator Variables/Methods → camelCase firstName calculateTax() Constants → UPPER_SNAKE_CASE MAX_SIZE · PI · APP_NAME Packages → all lowercase com.example.utils

Comments — Ignoring Code

Comments are lines the compiler completely ignores. They exist for humans reading the code.

Single-line comment

Java
1// This is a single-line comment 2int age = 25; // you can also put comments at the end of a line

Multi-line comment

Java
1/* 2 This is a multi-line comment. 3 It can span as many lines as you need. 4 The compiler ignores everything between the markers. 5*/ 6int salary = 50000;

Javadoc comment

Used to generate documentation automatically from your code:

Java
1/** 2 * Calculates the area of a rectangle. 3 * @param width the width of the rectangle 4 * @param height the height of the rectangle 5 * @return the area as a double 6 */ 7public double calculateArea(double width, double height) { 8 return width * height; 9}

💡 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:

CategoryKeywords
Data typesint, double, boolean, char, long, float, byte, short
Class & OOPclass, interface, extends, implements, new, this, super
Accesspublic, private, protected
Control flowif, else, switch, case, for, while, do, break, continue, return
Other commonstatic, final, void, null, true, false, import, package
Java
1// ❌ You cannot use keywords as variable names: 2int class = 5; // error — 'class' is a keyword 3String return = ""; // error — 'return' is a keyword 4boolean true = false; // error — 'true' is a keyword

A Complete Example — All Rules Applied

Here's a program that demonstrates every syntax rule covered on this page:

Java
1// File: BankAccount.java 2 3public class BankAccount { // PascalCase class name matches filename 4 5 // Constant — UPPER_SNAKE_CASE 6 static final double INTEREST_RATE = 0.05; 7 8 // Instance variables — camelCase 9 String accountHolder; 10 double balance; 11 12 // Method — camelCase, returns void 13 public void deposit(double amount) { 14 balance = balance + amount; // statement ends with ; 15 System.out.println("Deposited: " + amount); 16 System.out.println("New balance: " + balance); 17 } 18 19 // Entry point 20 public static void main(String[] args) { 21 BankAccount account = new BankAccount(); 22 account.accountHolder = "Arjun"; 23 account.balance = 1000.0; 24 25 account.deposit(500.0); 26 27 System.out.println("Account holder: " + account.accountHolder); 28 System.out.println("Interest rate: " + INTEREST_RATE); 29 } 30 31}

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

MistakeExampleFix
Missing semicolonSystem.out.println("Hi")Add ; at the end
Wrong capitalizationsystem.out.println(...)Use System.out.println(...)
Mismatched bracespublic class A { void m() { }Add closing } for class
Filename ≠ class nameFile: hello.java, class: HelloMatch exactly: Hello.java
Keyword as identifierint class = 5;Use a non-keyword name
Starting name with digitint 1count = 0;Start with a letter: int count1
Space in identifierString my name;Remove space: String myName;

The 3 Things to Remember From This Page

  1. Every statement ends with ; — declarations with {} do not. This single rule eliminates the most common category of compile errors.
  2. Java is fully case-sensitiveSystem, String, println must be capitalized exactly right. When code won't compile and you can't see why, check capitalization first.
  3. 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-sensitiveString and string are 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

TopicLink
Data types — int, String, boolean, doubleData Types →
Variables — declaring and using valuesVariables →
Operators — arithmetic, comparison, logicalOperators →
Comments in depthComments →
Write your first complete programFirst Java Program →
Syntax & Structure | DevStackFlow