Module 3 · Control Flow and Arrays — topic 1 of 4
Conditional Statements
if, else if and else, nested conditions, combining conditions with logical operators, and writing clear, correct decision logic.
Learning objectives
- Write if, if-else and else-if chains
- Combine conditions with &&, || and !
- Avoid the dangling-else and missing-brace traps
Definition
A conditional statement executes a block of code only when a boolean expression is true. Java's if statement requires the condition to be of type boolean.
Introduction
Programs constantly choose: is the password correct, is the stock low, did the student pass? The if statement is how Java makes those choices. Its syntax is the same as in C, with one important improvement: the condition must be a real boolean, so the classic C bug if (x = 5) does not compile.
Why it matters
Decision logic is where many business rules live — grading, discounts, validation — and small mistakes in boundaries (> versus >=) produce wrong results.
Clear conditions make code easier to test and review.
Detailed explanation
if (condition) { ... } runs the block when the condition is true. An optional else { ... } runs otherwise.
An else-if chain checks conditions in order and runs only the first block whose condition is true: if (m >= 90) ... else if (m >= 75) ... else .... Order matters — put the most specific or highest thresholds first.
Conditions are boolean expressions built from comparisons (< <= > >= == !=), method calls that return boolean (s.isEmpty(), list.contains(x)) and logical operators (&& || !).
Always use braces. Without them only the next single statement belongs to the if, and an else attaches to the nearest if — the *dangling else* problem.
Guard clauses handle special cases first and return early, keeping the main logic unindented: if (amount <= 0) return false;.
For many fixed values of one variable, a switch (next lesson) is often clearer than a long chain of else if.
Syntax
- The condition must be boolean:
if (count)is a compile error. - Only the first true branch of an else-if chain runs.
- Use braces even for one-line bodies.
Code examples
Grading with an else-if chain
95 -> A 82 -> B 40 -> C 39 -> F
Combining conditions
1900 is not a leap year 2000 is a leap year 2024 is a leap year 2026 is not a leap year
More examples
Validating a withdrawal with guard clauses
dispensed 2500, balance 2500 amount must be a multiple of 100 insufficient funds daily limit is 20000 card blocked invalid amount
Step-by-step explanation
- Each
ifchecks one rule and returns a message immediately when the rule fails — a guard clause. - The order of the rules is part of the design: a blocked card is reported before anything else.
amount % 100 != 0rejects amounts that the machine's notes can't make up.- Only when every check passes does the method reach the final
return, which describes the successful withdrawal. - The calls in
mainexercise every branch once, which is a good habit when testing conditional logic.
Expected output
Running “Validating a withdrawal with guard clauses” prints exactly:
Practical applications
- Form validation before saving data
- Pricing rules such as discounts and tax slabs
- Access control: checking roles and permissions
- Game logic: collisions, scores and win conditions
Best practices
- Always use braces.
- Test the boundary values of every condition (39, 40, 41).
- Extract complex conditions into well-named boolean variables or methods.
Common mistakes
Wrong order in an else-if chain
Avoid
Prefer
Only the first true condition runs, so broader conditions must come after narrower ones.
Semicolon after the condition
Avoid
Prefer
The semicolon is an empty statement that becomes the if's body, so the print always runs.
Important notes
- Java has no truthiness:
if (list)orif (count)doesn't compile; writeif (!list.isEmpty())orif (count != 0). - Comparing doubles with
==is risky because of rounding; compare with a small tolerance instead.
Key takeaways
- if/else-if/else runs the first branch whose condition is true.
- Conditions must be boolean expressions.
- Guard clauses and braces keep decision logic readable and safe.
Try it yourself
- 1Classify a triangle from three sides as equilateral, isosceles, scalene or invalid.
- 2Compute electricity charges with slabs: first 100 units ₹3, next 100 ₹5, rest ₹7.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhy doesn't `int n = 1; if (n) { ... }` compile in Java?
- BeginnerWhat is printed?