Decisions: if/else & switch
if, else if, else, nested conditions, the classic switch and modern switch expressions.
So far every statement ran from top to bottom. Real programs need to choose: charge shipping only for small orders, show an error only when the password is wrong. This lesson covers Java's decision-making tools: if, else, and switch. In the next lesson we look at loops.
if: run code only when a condition is true#
The condition inside ( ) must be a boolean expression. Unlike C or JavaScript, Java does not treat numbers as true/false: if (1) is a compile error.
if / else#
Exactly one of the two blocks runs.
else if chains#
When there are more than two possibilities, chain conditions. Java checks them top to bottom and runs only the first block whose condition is true:
Order matters: if you tested score >= 70 first, a 95 would get a C. Put the most specific (or highest) condition first.
Combining conditions#
Use the logical operators from the previous lesson:
Nested if#
You can put an if inside another. Keep nesting shallow, as deep nesting is hard to read:
A common way to flatten nesting is to handle special cases first and return early. You will see this pattern in the methods lesson.
Always use braces#
Braces are optional when a block has one statement, but skipping them invites bugs:
Only the first statement belongs to the if. Always write the braces and this bug can never happen.
Comparing values correctly#
Tip: write
"quit".equals(input)rather thaninput.equals("quit"). Ifinputisnull, the first form simply returnsfalsewhile the second throws aNullPointerException.
The classic switch statement#
When you branch on one value with many possible options, switch is cleaner than a long else if chain. It works with int (and smaller integer types), char, String and enums.
Each case label is a possible value; default runs when nothing matches. The break is crucial: without it, execution falls through into the next case:
Forgotten breaks are a notorious source of bugs, which is why modern Java added a better form.
The modern switch (Java 14+)#
Arrow cases (->) never fall through, can list several values separated by commas, and need no break:
switch as an expression
Even better, a switch can produce a value that you assign or return:
- A simple arrow case gives its value directly:
case 4, 6, 9, 11 -> 30; - A case that needs several statements uses a block, and
yieldhands back the value. - A switch expression must be exhaustive: every possible input must produce a value or throw. For
intorStringthat means adefaultis required. For enums, covering every constant is enough.
In Java 21, switch can also match on types and patterns (case Circle c -> ...). You will meet that in the modern Java lesson.
if or switch?#
A worked example: shipping calculator#
Common mistakes#
- Putting a semicolon after the condition:
if (x > 5);ends theifright there, and the block below always runs. - Using
=instead of==in a condition. - Comparing strings with
==. - Forgetting
breakin an old-style switch. Prefer arrow cases. - Ordering
else ifconditions so a broad case hides a narrower one.
What's next#
Your programs can now choose between paths. Next we make them repeat work with for, while and do-while loops.
Check your understanding
Quick quiz
1.What is printed?
int t = 25; if (t > 30) System.out.println("hot"); else if (t > 20) System.out.println("warm"); else if (t > 10) System.out.println("mild");2.In an old-style
switchstatement withcase 1:labels, what happens if you forgetbreak?3.In a modern
switchexpression, which keyword produces the value from a block{ ... }?
Finished reading?
Mark this lesson complete to track your progress.