Appearance
Lesson 01 · Conditionals — if / else
Objectives
After this lesson you will be able to:
- Write
if/else if/elsechains and reason about block scope. - Avoid the dangling-else and missing-braces traps the exam exploits.
- Remember that an
ifcondition must be aboolean— Java has no truthiness.
if, else if, else
An if runs its body only when a boolean condition is true. Java has no truthiness, so the condition cannot be an int or a reference.
java
int score = 72;
if (score >= 90) {
grade = 'A';
} else if (score >= 60) {
grade = 'C';
} else {
grade = 'F';
}Exam trap
The condition must be boolean. if (x = 5) only compiles if x is a boolean (it's an assignment, not a comparison); if (5) and if (someObject) never compile.
Braces, scope, and the single-statement body
If you omit braces, the if governs exactly one statement. Indentation is irrelevant to the compiler — only the syntax matters.
java
if (ready)
log("go");
fire(); // NOT part of the if — always runsA variable declared inside a block is scoped to that block:
java
if (cond) {
int local = 1;
}
// local is out of scope here — using it does not compileSDET note
Always use braces, even for one-liners. It removes the "second statement runs unconditionally" bug class entirely and keeps diffs clean when a branch later grows a second line.
The dangling else
An else binds to the nearest unmatched if, regardless of indentation. This is the classic dangling-else trap:
java
if (a)
if (b)
x();
else // binds to `if (b)`, NOT `if (a)`
y();If you intend the else to belong to the outer if, add braces:
java
if (a) {
if (b) x();
} else {
y(); // now belongs to `if (a)`
}Key Takeaways
- An
ifcondition must be aboolean; there is no truthiness in Java. - Without braces an
if/elsecontrols exactly one statement — later lines run unconditionally. - A bare
elsebinds to the nearestif; brace the outerifto redirect it. - Variables are block-scoped — they don't escape the
{ }they're declared in.
Lesson Quiz
What does this print?
boolean ready = false; if (ready) System.out.print("a"); System.out.print("b");Which condition does NOT compile?
Given a=true, b=false, what runs?
if (a) if (b) x(); else y();Is this legal?
if (cond) { int n = 1; } System.out.println(n);
Next: The switch. Run the matching code in labs/src/main/java/com/jse21/m02_flow/Conditionals.java.