Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 201 ยท Getting Started

Java Syntax

Learn the basic rules of Java syntax - statements and semicolons, blocks and braces, classes and methods, case sensitivity, naming conventions and reading compiler errors.

Every language has grammar, and Java's is strict: the compiler reads your whole program before running a single line, and anything that breaks the rules stops it with an error. That sounds harsh, but it's a gift. Mistakes that would silently misbehave in other languages are caught in seconds, with a line number.

The good news is that the rules are few and consistent. In this lesson you'll learn how Java code is put together, from statements and blocks up to classes and methods, along with the naming conventions every Java developer follows and a practical guide to reading the compiler's messages.

Statements and semicolons

A Java program is made of statements: individual instructions, executed one after another from top to bottom. Most statements end with a semicolon ;, the way English sentences end with a period:

Java Statements run in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The most common kinds of statement you'll write early on are:

  • Declarations, which create a variable: int width = 8;
  • Assignments, which change a variable: width = 10;
  • Method calls, which ask some code to do its job: IO.println("Hi");
  • Control-flow statements such as if, for and while, which decide what runs and how often. You'll meet them in if, else if and else.

Not every piece of code can stand alone as a statement. 5 + 3; computes a value and then throws it away, so Java rejects it with error: not a statement. A calculation has to go somewhere: into a variable, into println, or into another expression.

Where semicolons don't go

Semicolons end statements, not blocks. You don't put one after the closing brace of a method, a class, or an if block:

Java
void main() {               // no semicolon after the method header
    if (true) {
        IO.println("yes");  // semicolon ends this statement
    }                       // no semicolon after a block
}

A stray semicolon is usually harmless (Java treats a lone ; as an empty statement), but one after an if (...) or for (...) header is a classic bug: it becomes the whole body of the if or loop. You'll see that trap in the control-flow chapter.

Whitespace and line breaks

Java doesn't care about spaces, tabs or line breaks between the parts of your code. These three versions of a statement mean exactly the same thing:

Java
int total=price*quantity;
int total = price * quantity;
int total =
        price * quantity;

That freedom lets you break long statements across lines so they stay readable. It also means indentation is purely for humans: unlike Python, Java uses braces, not indentation, to decide what belongs together. Still, consistent indentation is not optional in practice. The Java convention is 4 spaces per level, with one statement per line.

Java Line breaks are up to you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The one place where whitespace matters is inside a string literal. Text between double quotes is printed exactly as written, spaces included. And a normal string literal can't contain a raw line break; to write multi-line text you'll use \n or a text block, both covered in Text Blocks and Escape Sequences.

Blocks and braces

Curly braces { } group statements into a block. Blocks appear everywhere: a method body is a block, a class body is a block, and so are the bodies of if statements and loops. Blocks nest inside each other, and every opening brace needs a matching closing brace.

Java
public class Main {                                  // class block starts
    public static void main(String[] args) {         // method block starts
        int score = 87;
        if (score >= 50) {                           // if block starts
            System.out.println("Passed");
        }                                            // if block ends
    }                                                // method block ends
}                                                    // class block ends

Java code puts the opening brace at the end of the line that starts the block, and the closing brace on its own line, lined up with the start of that line. This style is used by the JDK itself and by almost every Java project, so stick to it.

A block also limits where a variable is visible. A variable declared inside a block exists only until that block's closing brace. This is called scope; you'll explore it in Variables and Variable Scope.

When braces don't balance, the compiler can't tell where things end. A missing closing brace usually produces error: reached end of file while parsing: Java read the whole file and was still waiting for a }.

Classes and methods at a glance

Java organizes code in layers:

  1. A class is a container for related code. Every piece of Java code lives in one.
  2. Inside a class you write methods (named pieces of behavior) and fields (data the class keeps).
  3. Inside methods you write statements.

Statements can't appear directly in a class, outside any method. Methods, in turn, run only when something calls them, using the method name followed by parentheses:

Java A class with two methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Here main calls greeting twice, passing a different argument each time, and prints the text that greeting returns. You'll learn to write methods like this in Methods.

The dot . reaches inside something to use one of its members. In System.out.println, System is a class, out is a field inside it (the standard output stream), and println is a method of that stream. In IO.println, println is a method of the class IO.

A few more pieces of punctuation you'll see constantly:

Symbol Used for Example
( ) method calls and parameters, conditions, grouping math greeting("Ada"), (a + b) * 2
{ } blocks void main() { ... }
[ ] arrays String[] args
" " string literals (text) "Hello"
' ' char literals (one character) 'A'
; end of a statement int x = 5;
//, /* */ comments see Comments and Javadoc

Java is case-sensitive

To Java, uppercase and lowercase letters are different characters. count, Count and COUNT are three unrelated names, String is a type but string is not, and the main method must be called main, not Main.

This program fails because of a single capital letter. Run it and read the error, then fix it:

Java One wrong capital letter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler says cannot find symbol, then tells you exactly which symbol (variable Count) and where it looked (class Main). Change Count to count and the program runs.

Naming conventions

The compiler only enforces a few rules for names (letters, digits, _ and $; no starting digit; no keywords; see Java Keywords and Identifiers). On top of those rules, the Java world follows strong conventions. Code that ignores them still compiles, but it looks wrong to every other Java developer and makes code harder to read.

Kind of name Convention Examples
Classes, records, interfaces, enums PascalCase (each word capitalized), usually nouns Main, BankAccount, HttpClient
Methods camelCase, usually verbs println, calculateTotal, isEmpty
Variables and parameters camelCase count, firstName, maxScore
Constants (static final) UPPER_SNAKE_CASE MAX_SIZE, DEFAULT_TIMEOUT
Packages all lowercase, often a reversed domain java.util, com.example.shop
Type parameters (generics) a single capital letter T, E, K, V

Two tips that make names good, not just correctly shaped:

  • Say what it means. elapsedSeconds beats t, and customers beats list2. Short names like i are fine only for tiny loop counters.
  • Treat acronyms as words. Modern Java style writes HttpClient and parseJson, not HTTPClient and parseJSON (although you'll find both styles in older JDK classes like URLConnection).

Compact source files vs full classes

You've now seen two shapes of Java program. Here's how they differ in detail.

A compact source file (Java 25) contains methods and fields at the top level, with no class declaration around them. Java wraps them in an unnamed, final class for you. Compact files also get two conveniences:

  • The main method can be a plain void main(): no public, no static, no String[] args required.
  • Every public class from the core java.base module is available without an import, so List, Scanner, LocalDate and friends just work.
Java A compact file with a field and a helper method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same program written as a full class needs an explicit class, static on members used from static main, and an import for List:

Java
import java.util.List;

public class Main {
    static String course = "Java";

    static int square(int n) {
        return n * n;
    }

    public static void main(String[] args) {
        List<Integer> numbers = List.of(3, 4, 5);
        for (int n : numbers) {
            System.out.println(n + " squared is " + square(n));
        }
        System.out.println("Today we're learning " + course + ".");
    }
}

Classes in the java.lang package, such as String, Math, System, Integer and IO, never need an import, in any kind of file.

Use compact files for small programs, scripts and experiments. Switch to full classes as soon as your program grows into several classes, needs a package, or must be used by other code: an implicit class has no name you can refer to from elsewhere. Lessons in this course use whichever form explains the topic best.

Reading compiler errors

Compiler errors follow the same format every time:

TEXT
Main.java:3: error: cannot find symbol
    IO.println(Count);
               ^
  symbol:   variable Count
  location: class Main
1 error
  • Main.java:3 is the file and line number where Java noticed the problem.
  • After error: comes a short description.
  • The next line repeats your code, and the caret ^ points to the exact position.
  • Some errors add details, like the symbol: and location: lines above.
  • The last line counts the errors.

This program has three different mistakes. Run it, fix the first error the compiler reports, run again, and repeat until it works:

Java Fix the errors one at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

At first the compiler only reports the missing semicolon on line 3. Once you fix that, it reports two more errors at once: printn on line 5 and Days on line 6, both as cannot find symbol. Why didn't it say so earlier? The compiler works in phases. First it parses the text into a structure, and a broken structure stops it there. Only a program that parses correctly reaches the next phase, where names and types are checked. So fixing one error can reveal others. That's progress, not failure.

Here are the messages you'll meet most, and what they usually mean:

Message Usual cause
';' expected A missing semicolon, often at the end of the line before the caret.
cannot find symbol A typo, wrong capitalization, a variable used outside its scope, or a missing import.
incompatible types: String cannot be converted to int A value of the wrong type, such as text where a number is expected.
reached end of file while parsing A missing closing brace }.
unclosed string literal A missing closing double quote.
not a statement A value on its own line, like 5 + 3;, or a typo that breaks a statement.
variable x might not have been initialized Reading a local variable before giving it a value.
class, interface, annotation type, enum, record, method or field expected A statement outside any method, or an extra closing brace.

Two habits help enormously. Fix the first error first, because one mistake can cause a cascade of confusing follow-up errors. And look just before the caret: when Java expected something, it often notices only at the next token.

Compile errors vs runtime errors

Compile errors stop a program before it starts. Some problems, though, can only be detected while the program runs, such as dividing by a number that turns out to be zero. Those cause exceptions, which print a different kind of message:

Java A runtime error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This program compiles fine, prints its first line, and then stops with java.lang.ArithmeticException: / by zero, followed by a stack trace: a list of where the program was when it failed, including Main.java:5. You'll learn to handle exceptions in Exceptions and try-catch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these lines is NOT a valid Java statement inside a method?

    5 + 3; computes a value and discards it, so javac reports not a statement. The value has to be stored, printed or otherwise used.
  2. 2. A program is missing its final closing brace. What error do you expect?

    The compiler reads to the end of the file still waiting for the } that closes the method or class, so it reports that it reached the end of the file while parsing.
  3. 3. Following Java conventions, which name fits a class that represents a shopping cart?

    Class names use PascalCase: every word starts with a capital letter. camelCase is for variables and methods, and UPPER_SNAKE_CASE is for constants.
  4. 4. A program has a missing semicolon on line 3 and a misspelled method name on line 5. How many errors does the first compile report?

    javac parses first. A syntax error like a missing semicolon stops it before the phase that checks names, so the cannot find symbol error appears only after you fix line 3.
  5. 5. In a Java 25 compact source file, why can you use List without an import?

    Compact source files implicitly import the whole java.base module, which includes java.util.List. A normal class needs import java.util.List;.

Summary

  • Programs are made of statements that run top to bottom; most end with a semicolon, but blocks and method headers don't.
  • Whitespace and line breaks are free; indent with 4 spaces for readability. Spaces inside strings are kept.
  • Braces form blocks: class bodies, method bodies, if and loop bodies. They must balance.
  • Code lives in classes, behavior in methods, and statements inside methods. The dot . accesses members, as in System.out.println.
  • Java is case-sensitive: count and Count are different names.
  • Conventions: PascalCase classes, camelCase methods and variables, UPPER_SNAKE_CASE constants, lowercase packages.
  • Compact source files (Java 25) wrap top-level methods and fields in a class for you and import java.base automatically.
  • Compiler errors give file, line, message and a caret. Fix the first one first, and look just before the caret.

Next: Comments and Javadoc, where you'll learn to leave notes in your code and write documentation that tools can read.