Java Syntax

BEGINNER ~8 min read Tutorial

Java syntax borrows heavily from C and C++, so if you have written any of those languages much of this will look familiar. The differences are mostly in what Java removed: there are no global functions or variables, no multiple inheritance for classes, no operator overloading, and no pre-processor. What remains is a clean, predictable grammar that scales from tiny scripts to systems with millions of lines of code.

This tutorial is a tour of the rules: tokens, identifiers, literals, comments, statements, blocks, and the high-level structure of a .java file. We will not teach every keyword — many have their own tutorials — but you will leave knowing exactly what a Java source file looks like and what each piece is for.

1. File Structure

A Java source file is plain text with the .java extension. Its structure is fixed:

java
class=class="tok-str">"tok-cmt">// class="tok-num">1. optional package declaration
package com.dashboardesk.tutorials;

class=class="tok-str">"tok-cmt">// class="tok-num">2. optional imports
import java.util.Scanner;
import java.util.List;

class=class="tok-str">"tok-cmt">// class="tok-num">3. one or more top-level types
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

At the top, zero or more package and import declarations. Then one or more class, interface, enum or record declarations. There may be at most one public top-level type per file, and the file name must match that type's name.

2. Tokens

The Java compiler reads a source file as a stream of tokens. There are five kinds:

  • Identifiers — names you choose: HelloWorld, main, args, totalPrice.
  • Keywords — reserved words: class, public, static, void, int, if, while, and about forty more. You cannot use them as identifiers.
  • Literals — source-code representations of values: 42, 3.14, 'A', "text", true, null.
  • Operators and separators — + - * / = == != < > && || ! () {} [] ; , . and others.
  • Comments — three forms, all ignored by the compiler.

3. Identifiers and Naming

An identifier starts with a letter, underscore or dollar sign, followed by letters or digits. By convention:

  • Class and interface names use UpperCamelCase: CustomerAccount, Listenable.
  • Method and variable names use lowerCamelCase: computeTotal, firstName.
  • Constants use UPPER_SNAKE_CASE: MAX_RETRIES, DEFAULT_TIMEOUT_MS.
  • Packages use all-lowercase, reverse-DNS: com.dashboardesk.tutorials.
Unicode in identifiers

Java allows Unicode letters in identifiers, so double prix or int 番号 technically compile. In practice, English ASCII identifiers are the norm in production code because they make the code easier to read for an international team.

4. Comments

Java has three comment forms. The first two are for human readers and are stripped by the compiler; the third is processed by javadoc to produce API documentation.

java
class=class="tok-str">"tok-cmt">// a single-line comment - the rest of the line is ignored

class=class="tok-str">"tok-cmt">/* a multi-line comment -
   everything between slash-star and star-slash is ignored */

/** A Javadoc comment.
 *  Starts with slash-star-star, ends with star-slash.
 *  @param args command-line arguments
 *  @return nothing
 *  @throws NullPointerException never, but tags are illustrative
 */

Javadoc comments are how the official Java API is documented. The same tags (@param, @return, @throws) drive the auto-generated HTML reference at docs.oracle.com. Get into the habit of writing a short Javadoc on every public method.

5. Statements and Blocks

A statement is a single action terminated by a semicolon. A block is a group of zero or more statements enclosed in curly braces. Blocks can appear wherever a single statement is allowed, which is why if (x) { y(); } works — the block is just an inline list of statements.

java
class=class="tok-str">"tok-cmt">// single statement
System.out.println("one");

class=class="tok-str">"tok-cmt">// block of two statements
{
    System.out.println("two");
    System.out.println("three");
}

class=class="tok-str">"tok-cmt">// block is allowed wherever a statement is allowed
if (x > class="tok-num">0) {
    System.out.println("positive");
    logPositive(x);
}

Java does not use indentation to denote structure, unlike Python. Whitespace is mostly ignored. Indentation is purely for human readability; most editors and IDEs will indent consistently for you automatically.

6. The main Method Signature

The JVM entry point has an exact signature:

java
public static void main(String[] args) {
    class=class="tok-str">"tok-cmt">// entry point invoked by `java YourClass`
}

Every part matters: public so the JVM can call it from outside the class; static so the JVM does not need to instantiate your class first; void because the JVM does not expect a return value (use System.exit for an exit code); the name main lowercase; the parameter String[] args. Since Java 21 you can also write it as String... args (varargs).

7. Packages and Imports

A package groups related classes and avoids name collisions. The package declaration must be the first line of the file:

java
package com.dashboardesk.tutorials;

class=class="tok-str">"tok-cmt">// single-type import
import java.util.Scanner;

class=class="tok-str">"tok-cmt">// on-demand import (everything in java.util)
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
    }
}

Imports tell the compiler which classes you mean when you write short names like Scanner or List. They are purely a compile-time convenience; they do not affect the produced .class file size. java.lang is imported automatically, which is why String, System and Math are available without an import.

Exercises

  1. Write a HelloWorld class in a package com.example. Compile and run it; notice that the bytecode lives in a directory structure mirroring the package name.
  2. Add a Javadoc comment above your main method describing what it does. Run javadoc -d docs HelloWorld.java to generate HTML.
  3. Try to use a keyword as a variable name (int class = 1;) and read the compiler error.
  4. Rewrite a short snippet using braces around a single-statement if, then remove the braces — confirm the behaviour is identical.