JB Header

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 -
  1. An optional package declaration, which says which package the classes belong to.
  2. Optional import statements, which let you use classes from other packages by their short names.
  3. 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.
Inside a class are its members - fields (variables that belong to the class) and methods (named blocks of code). Here is a small program which shows each of these parts.
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);
  }
}
 OUTPUT of the above code
Order date : 2026-10-22
Total      : 885.0
Explanation of the code
  • import java.time.LocalDate; lets the code write LocalDate instead of the full name java.time.LocalDate. Classes in java.lang, such as String and System, never need importing.
  • The class has one field, TAX_RATE, and two methods, totalWithTax() and main(). The program starts in main(), which calls totalWithTax().
  • This file has no package declaration, so its class is in the unnamed package - fine for small examples. Real applications always use packages.
Statements and blocks A statement is a single instruction, and in Java most statements end with a semicolon ; - 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
Note - Blocks themselves, and statements such as 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; and int 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, Total and TOTAL are three different names. System must be written with a capital S, and main in lower case.
Identifiers - naming rules An identifier is a name you give to a class, method, variable or other element. Java's rules for identifiers are -
  • It can contain letters, digits, the underscore _ and the dollar sign $.
  • It cannot start with a digit. total2 is valid; 2total is not.
  • It cannot contain spaces or other symbols, such as - or #.
  • It cannot be a Java keyword, such as class or int, or one of the literals true, false and null. A single underscore _ on its own is also reserved.
  • There is no length limit.
Breaking these rules is a compile error. In this example, a variable name starts with a digit -
An invalid identifier
//BadName.java
public class BadName {
  public static void main(String[] args) {
    int 2ndPlace = 10;
    System.out.println(2ndPlace);
  }
}
 OUTPUT on compiling the above code
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
Because 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.
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.
  • 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.
Choose names which describe what something holds or does - 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, and void for "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, and assert.
  • Reserved but unused: const and goto.
Note - Newer Java versions added contextual keywords, such as 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's javadoc tool turns them into HTML documentation. The comment above OrderSummary earlier 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
}
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.