Java Syntax and Statements Explained

Java syntax is the set of rules that tells the compiler how to read your program.

Lesson 2 of 127Beginner14 min read

Java syntax is the set of rules that tells the compiler how to read your program. A statement performs an action, such as declaring a variable or printing a message. An expression produces a value, such as the result of adding two numbers. Understanding that difference makes unfamiliar Java code easier to read because you can identify what each part contributes before running it.

This lesson uses ordinary Java 17 programs. Start with the smallest complete program, then follow a calculation and a conditional block. You do not need to understand every keyword in the opening line immediately; first learn where instructions belong and how Java marks their boundaries.

The shape of a complete Java program

A traditional Java program places methods inside a class. The class gives the source code a named container, and the main method provides the starting point when you launch that class. The opening brace after the class declaration begins the class body. Another pair of braces surrounds the main method body. Instructions that run at startup belong inside that method, rather than directly between the class braces.

Declarations, expressions and assignments

The declaration int tickets = 8; introduces a variable called tickets and gives it an initial integer value. The type describes what values the variable can store. The name lets later statements refer to that storage. The initializer supplies its first value. The semicolon finishes this declaration statement.

In tickets - 3, the subtraction is an expression because it produces a number. In int remaining = tickets - 3;, that expression appears inside a declaration. In remaining = 2;, assignment replaces the value already stored in remaining. Read an assignment from its right side to its left side: Java evaluates the right side before storing its result. The equals sign here is assignment, not a mathematical claim that both sides stay equal forever.

Semicolons end simple statements

Declarations, assignments, method-call statements and return statements normally end with semicolons. A line break does not take their place. Conversely, a long expression may span several lines before its final semicolon.

Do not add a semicolon merely because you see a closing brace. Class declarations, method declarations and ordinary if blocks do not need one after their closing brace. There are special forms, such as do-while loops, that do require one; learn those with their own syntax. An unexpected semicolon immediately after an if condition creates an empty statement, so the following block may run without the intended condition.

Braces determine the boundaries

A block is a sequence of statements surrounded by braces. Blocks let a method, condition or loop treat several instructions as one group. Indentation makes the grouping visible to a reader, but Java uses braces to decide which statements belong together. Moving spaces around does not change that grouping.

When an if condition is true, Java executes the statements in its block. When it is false, Java skips that block. Code after the closing brace continues in either case. This distinction explains why a confirmation printed outside a condition appears even when the condition fails. For beginner code, keep braces even when a condition contains only one statement: adding another instruction later then preserves the intended boundary.

Names, case and string punctuation

Java distinguishes uppercase and lowercase letters. System.out.println is not interchangeable with system.out.println, and the variables total and Total have different names. Names such as System and String come from the Java library. Your own class and variable names must be written consistently wherever you use them.

Double quotes surround a string literal, which represents text. The quotes are syntax and do not appear in the printed output. Parentheses surround arguments supplied to a method. In System.out.println("Ready");, the quoted text is the argument, the parentheses complete the call, and the semicolon completes the statement. A missing quote can make later characters look like part of the string, so a compiler may report an error after the place where the mistake began.

Compile one change at a time

Save each worked example under the filename matching its public class. From that directory, run javac --release 17 Greeting.java and then java Greeting. Use the class name without the .class extension when launching. Repeat this pattern for the other examples with their own names.

Practice with explained solutions

Task 1. Declare an integer called boxes with value 12, subtract 5 into a separate variable, then print the result.

Solution. The new variable should contain 7. State which part is the expression and which entire line is the declaration statement.

Task 2. Modify DoorMessage so a second message, Please close the door, prints only when open is true.

Solution. Place both conditional messages inside the same pair of braces; leave Check complete after that block.

Java Summary

  • Statements perform actions; expressions produce values used by those statements.
  • Braces define blocks, while semicolons finish ordinary declarations, assignments and calls.
  • Save a public class in its matching filename before compiling and launching it.
  • Continue with Java output.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A minimal starting point

Save this complete program as Greeting.java. Compile with javac --release 17 Greeting.java and run with java Greeting.

Java
public class Greeting {
    public static void main(String[] args) {
        System.out.println("Welcome to Java");
    }
}
Output
Welcome to Java
Line-by-line explanation
  1. Lines 1 to 5The main method contains one executable statement. Java calls println with the string Welcome to Java, so the output contains that text and a line ending. The class and method braces organize the instruction but do not print anything. Try changing only the string first. Then remove the semicolon and compile again to see how a syntax error differs from changed output. Restore the semicolon before continuing.
Example 2

Follow a calculation

Save this complete program as TicketCount.java. Compile with javac --release 17 TicketCount.java and run with java TicketCount.

Java
public class TicketCount {
    public static void main(String[] args) {
        int tickets = 8;
        int sold = 3;
        int remaining = tickets - sold;
        System.out.println(remaining);
    }
}
Output
5
Line-by-line explanation
  1. Lines 1 to 8The first two declarations store 8 and 3. The next declaration evaluates tickets - sold using those stored values and initializes remaining to 5. The final statement prints remaining; it does not repeat the subtraction. If you subsequently change sold, remaining keeps its previous value until you assign a newly calculated result. This is an important difference between a stored value and a formula in a spreadsheet.
Example 3

A block controlled by a condition

Save this complete program as DoorMessage.java. Compile with javac --release 17 DoorMessage.java and run with java DoorMessage.

Java
public class DoorMessage {
    public static void main(String[] args) {
        boolean open = false;
        if (open) {
            System.out.println("Enter");
        }
        System.out.println("Check complete");
    }
}
Output
Check complete
Line-by-line explanation
  1. Lines 1 to 9The condition reads the boolean value false, so Java skips the println inside its braces. The second println sits after the block and therefore executes. Set open to true and the program prints Enter before Check complete. Adding a semicolon after if (open) would break that intended relationship even though the source can still compile.

Common Java Mistakes

Trusting indentation instead of braces

Do not mistake indentation for execution rules. If an unbraced if controls one println and another indented println follows it, only the first is conditional. Add braces around both statements when both must depend on the condition. Also avoid editing several punctuation marks at once after a compiler error; restoring the earliest broken statement often removes the later errors.

Java FAQ

Does every Java line need a semicolon?

No. Simple statements usually do, but class, method and ordinary control-flow block boundaries use braces. Think in grammatical units rather than physical lines.

Can a program contain several classes?

Yes, but the beginner examples use one public top-level class per file to make naming and execution straightforward.

Is Java sensitive to spaces and indentation?

No. Java uses spaces only to separate words such as int and count, and braces decide which statements belong to a block. Indentation is for human readers, so keep it consistent with the braces: misleading indentation is a common source of bugs that the compiler won't warn you about.

What is the difference between a statement and an expression?

An expression produces a value, such as price * 2 or name.length(). A statement performs an action and is a complete instruction, such as int total = price * 2;. Many statements contain expressions; a method call followed by a semicolon is both.

Do I always need a class to run Java code?

Traditional Java programs need a class with a main method. For quick experiments, jshell runs single lines without one. Java 25 also allows compact source files, where a file can contain just a void main() method, but most code you'll read still uses the classic class-and-main structure.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does TicketCount print if sold becomes 4?

Multiple choicemedium

Why does DoorMessage still print Check complete when open is false?

Java Quiz

2 questions to check what you learned.

  1. Which part produces a value?

    • tickets - sold
    • The closing class brace
    • A comment
  2. What determines an if block boundary?

    • Indentation
    • Braces
    • The filename