Conditional Statements
Conditions let your program take different paths depending on data.
On this page · 5 min · Beginner
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 30, 2026
In simple words#
An if statement is a railway junction: depending on the signal (condition), the train goes down exactly one track.
- if / else if / else
- Choose one branch by condition.
- switch expression
- Pick a value by case using ->.
- yield
- Return a value from a block inside a switch expression.
Learning objectives#
- Write if/else chains
- Use switch statements
- Use modern switch expressions
- Avoid deep nesting
Explanation#
if (condition) { … } else if (…) { … } else { … } — the first true branch runs.
Classic switch needs break to stop fall-through.
Switch expressions (Java 14+) use case X -> value, return a value and do not fall through.
Return early or use guard clauses to avoid deeply nested ifs.
Code example: Grades and delivery days#
int marks = 82;
String grade;
if (marks >= 90) grade = "A+";
else if (marks >= 75) grade = "A";
else if (marks >= 60) grade = "B";
else grade = "C";
String day = "SAT";
int deliveryDays = switch (day) {
case "MON", "TUE", "WED", "THU", "FRI" -> 2;
case "SAT" -> 3;
case "SUN" -> {
System.out.println("No dispatch on Sunday");
yield 4;
}
default -> throw new IllegalArgumentException("Unknown day: " + day);
};
System.out.println("Grade " + grade + ", delivery in " + deliveryDays + " days");
Grade A, delivery in 3 days
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- The if chain stops at the first true condition.
- Several labels share one case.
- A block case uses yield to return its value.
- default throws for unexpected input.
Real-world use case#
Order systems use switch expressions to map order status to messages and delivery estimates.
Common mistakes#
Execution falls through to the next case. Prefer switch expressions.
Use "SAT".equals(day).
Best practices#
- Prefer switch expressions
- Use guard clauses
- Always handle default
- Keep conditions readable
Remember this#
First true branch wins.
case X -> value: no fall-through.
yield returns from a block case.
Practice exercise#
Your task: Return "Weekend" for SAT/SUN and "Weekday" otherwise with a switch expression.
Show solution
String type = switch (day) {
case "SAT", "SUN" -> "Weekend";
default -> "Weekday";
};
Mini quiz#
What keyword returns a value from a block in a switch expression?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.