Braces on if statements
Optional for a single statement. Use them anyway.
Java allows a single statement without braces:
if (x > 0)
System.out.println("positive");
Legal, and a bad habit. Two well-documented bugs come from it.
Adding a line
if (x > 0)
System.out.println("positive");
System.out.println("also positive"); // always runs
The indentation says both lines are conditional. The language says only the first is. The compiler is right and silent, and the code looks correct to a reader skimming it.
With braces this cannot happen. The person adding the line puts it inside them.
The dangling else
if (a)
if (b)
doX();
else
doY();
The indentation suggests doY() runs when a is false. It does not: else binds to the nearest unmatched if, so doY() runs when a is true and b is false. The formatting is a lie.
The famous one
This pattern caused a real security failure — the “goto fail” bug in Apple’s TLS implementation in 2014:
if (something)
goto fail;
goto fail; // always executed
A duplicated line, unbraced, meant certificate verification returned success without checking. The same shape is available in Java, and only the consequences differ.
The convention
Braces on every if, else, for, while and do, even for one statement. Every mainstream Java style guide says so, and every linter can enforce it.
The cost is two characters and a line. The benefit is that a whole category of edit-introduced bug becomes impossible.
The one exception people allow
A guard clause on one line, where there is nothing to add to:
if (list == null) return;
Some style guides permit this because the statement and the condition are on the same line, so there is no misleading indentation to create. Others require braces here too. Either is defensible; being consistent matters more than which you pick.
Ternary instead
When an if only chooses between two values, the conditional operator is often clearer and has no brace question at all:
int max = (a > b) ? a : b;
Use it for choosing a value. Do not use it for choosing an action.