Java Syntax Basics: Statements, Identifiers, Keywords
Introduction
Every language has rules about how its sentences are put together, and Java is no different. This tutorial covers the basic syntax of Java - the building blocks that every Java program is made of. We will start with the overall structure of a Java source file. We will then look at statements and blocks, and at Java's rules for whitespace and case. Next we will learn the rules and conventions for naming things - identifiers - and look at Java's keywords. Lastly, we will see the three kinds of comments.
(Note - This tutorial assumes you have run the Hello World programClick to read tutorial: Java Hello World Program Explained Line by Line.) The structure of a Java source file A Java source file contains, in this order -
OUTPUT of the above code
Explanation of the code
Statements and blocks
A statement is a single instruction, and in Java most statements end with a semicolon
Note - Blocks themselves, and statements such as
OUTPUT on compiling the above code
Because
Naming conventions
Besides the rules, Java developers follow naming conventions. The compiler does not enforce them, but code which ignores them is hard for other Java developers to read.
Good comments explain why the code does something, not what it does - clear names should already say what.
Summary
In this tutorial we first looked at the structure of a Java source file - the package declaration, imports and a class containing fields and methods. We then saw that statements end with semicolons and are grouped into blocks with curly braces, that whitespace is mostly ignored, and that Java is case-sensitive. Next we learned the rules for identifiers and the naming conventions for classes, methods, variables, constants and packages. We then went through Java's keywords, grouped by purpose. Lastly, we saw single-line, multi-line and Javadoc comments. In the next tutorial, we will look at variablesClick to read tutorial: Variables in Java: Declaration, Initialization and Scope in detail.
(Note - This tutorial assumes you have run the Hello World programClick to read tutorial: Java Hello World Program Explained Line by Line.) The structure of a Java source file A Java source file contains, in this order -
- An optional
packagedeclaration, which says which package the classes belong to. - Optional
importstatements, which let you use classes from other packages by their short names. - One or more type declarations - usually one class. Only one of them can be
public, and it must have the same name as the file.
The parts of a Java source file
//OrderSummary.java
import java.time.LocalDate;
/**
* Prints a summary of an order.
*/
public class OrderSummary {
static final double TAX_RATE = 0.18; // a field (constant)
static double totalWithTax(double amount) { // a method
return amount + amount * TAX_RATE;
}
public static void main(String[] args) {
int quantity = 3;
double price = 250.0;
double total = totalWithTax(quantity * price);
System.out.println("Order date : " + LocalDate.of(2026, 10, 22));
System.out.println("Total : " + total);
}
}
Order date : 2026-10-22 Total : 885.0
import java.time.LocalDate;lets the code writeLocalDateinstead of the full namejava.time.LocalDate. Classes injava.lang, such asStringandSystem, never need importing.- The class has one field,
TAX_RATE, and two methods,totalWithTax()andmain(). The program starts inmain(), which callstotalWithTax(). - This file has no
packagedeclaration, so its class is in the unnamed package - fine for small examples. Real applications always use packages.
; - declaring a variable, assigning a value, or calling a method. A block is a group of statements inside curly braces { }. Blocks form the bodies of classes, methods, loops and if statements, and can be nested inside each other.
Statements and blocks
int count = 5; // a declaration statement
count = count + 1; // an assignment statement
System.out.println(count); // a method call statement
if (count > 5) { // a block starts
System.out.println("More than 5");
count = 0;
} // the block ends
if and loops which end with a block, do not need a semicolon after the closing brace.
Whitespace and case sensitivity
- Whitespace is mostly ignored: Spaces, tabs and line breaks between the parts of a statement do not matter to the compiler.
int x=5;andint x = 5;mean the same thing, and one statement can be spread over several lines. Use whitespace and indentation to make code easy to read - the usual style is to indent the contents of each block by 2 or 4 spaces. - Java is case-sensitive:
total,TotalandTOTALare three different names.Systemmust be written with a capital S, andmainin lower case.
- It can contain letters, digits, the underscore
_and the dollar sign$. - It cannot start with a digit.
total2is valid;2totalis not. - It cannot contain spaces or other symbols, such as
-or#. - It cannot be a Java keyword, such as
classorint, or one of the literalstrue,falseandnull. A single underscore_on its own is also reserved. - There is no length limit.
An invalid identifier
//BadName.java
public class BadName {
public static void main(String[] args) {
int 2ndPlace = 10;
System.out.println(2ndPlace);
}
}
BadName.java:4: error: not a statement
int 2ndPlace = 10;
^
BadName.java:4: error: ';' expected
int 2ndPlace = 10;
^
BadName.java:5: error: ')' or ',' expected
System.out.println(2ndPlace);
^
BadName.java:5: error: ';' expected
System.out.println(2ndPlace);
^
4 errors
2ndPlace starts with a digit, the compiler reads 2 as a number and cannot make sense of the rest, so it reports several confusing errors on both lines. When you see a burst of errors like this, look carefully at the names on the first line it mentions.
- Classes and interfaces: PascalCase - each word starts with a capital letter.
OrderSummary,ArrayList. - Methods and variables: camelCase - like PascalCase, but the first letter is lower case.
totalWithTax(),quantity,firstName. Method names are usually verbs. - Constants: all capitals with underscores.
TAX_RATE,MAX_VALUE. - Packages: all lower case, often a reversed domain name.
com.javabrahman.orders.
totalPrice rather than tp. Avoid $ in your own names; it is used in names generated by the compiler and tools.
Keywords
Keywords are words with a special meaning to the compiler, so they cannot be used as identifiers. All keywords are in lower case. You will learn them gradually through this series; here they are grouped by what they do -- Primitive types:
boolean,byte,char,short,int,long,float,double, andvoidfor "no value". - Control flow:
if,else,switch,case,default,for,while,do,break,continue,return. - Classes and objects:
class,interface,enum,extends,implements,new,this,super,instanceof,package,import. - Modifiers:
public,protected,private,static,final,abstract,synchronized,volatile,transient,native,strictfp. - Exceptions:
try,catch,finally,throw,throws, andassert. - Reserved but unused:
constandgoto.
var, record, yield, sealed and permits. These have a special meaning only in certain places, so older code which used them as variable names still compiles.
Comments
Java has three kinds of comments, all ignored by the compiler -- Single-line comments: start with
//and run to the end of the line. - Multi-line comments: start with
/*and end with*/, and can span many lines. - Documentation (Javadoc) comments: start with
/**and end with*/. Placed just before a class, method or field, they describe it, and the JDK'sjavadoctool turns them into HTML documentation. The comment aboveOrderSummaryearlier is a Javadoc comment.
The three kinds of comments
// A single-line comment
/* A multi-line comment
which spans two lines */
/**
* Returns the amount with tax added.
* @param amount the amount before tax
* @return the amount after tax
*/
static double totalWithTax(double amount) {
return amount + amount * TAX_RATE; // comments can also follow code
}
Java Fundamentals Tutorials
JShell Tutorial: Java's Interactive REPL with ExamplesClick to read tutorial: JShell Tutorial: Java's Interactive REPL with Examples Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators
JShell Tutorial: Java's Interactive REPL with ExamplesClick to read tutorial: JShell Tutorial: Java's Interactive REPL with Examples Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples Java var Keyword: Local Variable Type InferenceClick to read tutorial: Java var Keyword: Local Variable Type Inference Java Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators