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. This chapter walks through the rules you'll rely on for the rest of the book.

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.

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);

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 missing one.

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

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.

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.

Practice

Practice

Which statement about Java syntax is correct?