Beginner level · Module 2: Decisions, Loops and Methods in Java · Lesson 1 of 3
Making Decisions with if and switch
Use comparisons, logical operators, if/else chains and switch to choose what a program does.
In this lesson you will
- Write conditions with comparison and logical operators
- Choose between if/else chains and switch
Key concepts
boolean expression&& and ||else ifswitch expression
The lesson
A condition is a boolean expression such as score >= 50 or paid == total. Combine conditions with && (and), || (or) and ! (not). Compare Strings with equals(), not ==, because == checks whether two variables point to the same object, not whether the text is the same.
An if/else if/else chain tests conditions in order and runs the first branch that is true. Put the most specific conditions first; otherwise a broad condition earlier in the chain hides them.
Modern Java (14 and later) has switch expressions that return a value: String day = switch (n) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Unknown"; }; They are clearer than long if chains when one value is compared against many fixed options.
Step by step
- Read a mark from 0 to 100 into an int.
- Use an if/else if chain to print a grade band.
- Rewrite a menu choice with a switch expression.
- Test boundary values such as 49, 50 and 100.
Practice activity
Write a grade calculator that prints Distinction (75+), Credit (60–74), Pass (50–59) or Fail, and rejects marks outside 0–100.
Expected result: Marks 75, 60, 50, 49, 101 and -5 produce Distinction, Credit, Pass, Fail and two 'invalid mark' messages.
Check your understanding
-
How should two Strings be compared for equal text?
Show answer
With a.equals(b), not a == b.
-
Why does the order of else-if conditions matter?
Show answer
Only the first true branch runs, so a broad condition placed first can hide more specific ones.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.