Block Statements vs Single Statements
What you'll learn: You'll discover when you need curly braces {} around your if, else, and else if statements—and why skipping them can lead to surprising bugs.
The Core Idea
In Java, when you write an if or else, you can follow it with either:
- A single statement (no braces needed)
- A block statement (multiple statements wrapped in
{})
Here's the thing: if you omit the braces, Java only associates the very next statement with your condition. Everything after that runs regardless of the condition!
Single Statement (No Braces)
if (temperature > 100)
System.out.println("Water is boiling!");
This works fine—one condition, one action.
The Hidden Danger
if (temperature > 100)
System.out.println("Water is boiling!");
System.out.println("Turn off the stove!"); // ALWAYS runs!
Surprise! The indentation looks like both lines belong to the if, but Java only binds the first println to the condition. The second one always executes. This is a classic bug.
Always Use Braces (Best Practice)
if (temperature > 100) {
System.out.println("Water is boiling!");
System.out.println("Turn off the stove!");
}
Now both statements are clearly part of the if block. The braces make your intent explicit and prevent accidental logic errors.
Think of It Like a Container
Braces are like a box that groups statements together. Without the box, only the very next item gets associated with your condition—even if your indentation suggests otherwise. Java ignores your formatting!
Key Takeaway: Always use curly braces {} with if, else, and else if statements, even for single statements—it prevents common bugs and makes your code clearer and safer to modify later.