W3docs

Java Syntax

Understand Java's basic syntax — statements, blocks, identifiers, keywords, case sensitivity, and the structure of a Java source file.

Java syntax is what gives a .java file its shape: where statements end, how blocks of code are grouped, which words have special meaning to the compiler, and which characters are legal in a name. These rules are checked at compile timejavac refuses to produce a .class file until they are all satisfied — so getting them right early saves you a lot of confusing errors later.

This chapter covers the rules you'll rely on for the rest of the book: the structure of a source file, statements, blocks, identifiers, keywords, comments, case sensitivity, and whitespace.

A complete Java source file

Every standalone Java program needs at least one class with a main method. Here is the minimum file:

public class App {
    public static void main(String[] args) {
        System.out.println("Hello, syntax!");
    }
}

Three things are happening on the page:

  • The class declaration public class App { ... } wraps everything inside a class.
  • The method declaration public static void main(String[] args) { ... } is the program's entry point.
  • The statement System.out.println(...) does the work.

The file must be saved as App.java because the public class is called App. This is a hard rule: a source file may contain at most one public class, and the file name must match that class name exactly, including capitalization. See Java Hello World for the full compile-and-run cycle.

Statements end with a semicolon

A Java statement is an instruction that tells the program to do something. Each statement ends with a semicolon:

int score = 0;
score = score + 5;
System.out.println(score);

Because the semicolon — not the line break — is what ends a statement, you can spread a long statement across several lines, or (less readably) put several statements on one line:

int total = 1 + 2 + 3
          + 4 + 5;        // one statement, two lines
int a = 1; int b = 2;     // two statements, one line

Leaving off a semicolon is the most common beginner mistake. The compiler will point at the line it noticed the problem on, which is usually the line after the one that is actually missing the semicolon — so when you see "';' expected", check the line above the one flagged.

Blocks group statements

Curly braces { and } group statements into a block. Class bodies, method bodies, loop bodies, and if bodies are all blocks:

public class Counter {        // class block opens
    public static void main(String[] args) {   // method block opens
        for (int i = 0; i < 3; i++) {          // loop block opens
            System.out.println(i);
        }                                       // loop block closes
    }                                           // method block closes
}                                               // class block closes

Indentation isn't part of the syntax (the compiler ignores whitespace), but every reader will expect four spaces per nested block. Most IDEs format this for you on save.

Identifiers

An identifier is any name you choose — for a class, a method, a variable, a constant. The rules:

  • Starts with a letter, _, or $.
  • After the first character, may also contain digits.
  • Case-sensitive: total and Total are different names.
  • Cannot be a reserved keyword (class, int, return, etc.).
  • No length limit.

Legal: total, lineCount, _temp, $jquery, userName2. Illegal: 2lines (starts with digit), line-count (hyphen), class (keyword).

Those are the rules the compiler enforces. On top of them, Java has strong naming conventions that the compiler ignores but every Java developer expects:

  • Classes use UpperCamelCaseBankAccount, HttpServer.
  • Methods and variables use lowerCamelCaseaccountBalance, parseInput.
  • Constants use UPPER_SNAKE_CASEMAX_SIZE.

Following them is not optional in practice. The Java Variables chapter goes deeper on naming and declaring data.

Keywords

Java reserves about 50 words for the language itself. You can't use them as identifiers. The ones you'll see most often:

abstract  case      do        finally    int         private     synchronized  throws
assert    catch     double    float      interface   protected   this          transient
boolean   char      else      for        long        public      throw         try
break     class     enum      if         new         return      void          while
byte      continue  extends   import     null        short       volatile      switch

Plus a few contextual keywords added in modern Java that are only special in certain positions (var, yield, record, sealed, permits).

Case sensitivity

Java is case-sensitive everywhere — class names, method names, variables, keywords. System is not the same as system, and if is not the same as If. The compiler will tell you "cannot find symbol" if you mistype a name.

Whitespace and line breaks

Spaces, tabs, and newlines between tokens are equivalent. The compiler doesn't care whether you write:

int x=1+2;

or:

int x = 1 + 2;

Use whichever is more readable; the standard style sheet (and your IDE's formatter) will give you the right answer.

The one place whitespace does matter is inside string and character literals: "Hello world" and "Helloworld" are different values, and spaces between them are kept exactly as typed.

Comments

A comment is text the compiler ignores entirely. Java has three forms:

// line comment — runs to the end of the line

/* block comment —
   can span multiple lines */

/**
 * Javadoc comment — a block comment whose first character
 * is an extra asterisk. Tools generate API docs from these.
 */

Use comments to explain why something is done, not to restate what the code obviously does. The Java Comments chapter covers each form and when to reach for it.

Warning

Block comments do not nest. Writing /* outer /* inner */ */ ends the comment at the first */, and the leftover */ becomes a syntax error. To comment out a region that already contains /* ... */, use line comments (//) instead.

A program that exercises the rules

java— editable, runs on the server

Notice every statement ends with ;, the class and method bodies are blocks { ... }, the names x, y, and product are valid identifiers, and the file would be saved as Demo.java.

What's next

The next chapter, Java Output, covers the three printing methods (print, println, printf) you'll use to inspect what your programs are doing. From there, Java Data Types explains what kinds of values your identifiers can hold.

Practice

Practice
Which statement about Java syntax is correct?
Which statement about Java syntax is correct?
Was this page helpful?