Selection (if/else)
IB Syllabus: B2.3.2 — Construct algorithms using selection: if, else if, else, nested if, and boolean conditions.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Code Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- Connections
Key Concepts
Selection allows a program to make a decision and follow different paths depending on whether a condition is true or false.
| Structure | When to use |
|---|---|
if | One action when a condition is true |
if-else | Two different paths — true or false |
if-else if-else | Multiple conditions checked in order |
Nested if | A decision inside another decision |
Relational Operators
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | score == 100 |
!= | Not equal to | input != 0 |
< | Less than | age < 18 |
> | Greater than | temp > 30 |
<= | Less than or equal to | marks <= 50 |
>= | Greater than or equal to | grade >= 90 |
Boolean (Logical) Operators
| Operator | Meaning | Example |
|---|---|---|
&& | AND — both must be true | age >= 13 && age <= 17 |
\|\| | OR — at least one must be true | score < 0 \|\| score > 100 |
! | NOT — reverses the boolean | !isValid |
Use
==to compare primitives (int,boolean,char). To compare Strings, always use.equals():if (name.equals("Alice")) { ... } // correct if (name == "Alice") { ... } // WRONG — compares memory addresses
Worked Examples
Example 1: Simple if-else — Pass or Fail
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter your score: ");
int score = input.nextInt();
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
How it works:
- If the score is 50 or above,
"Pass"is printed. - Otherwise (score below 50),
"Fail"is printed. - Only one branch ever runs — they are mutually exclusive.
Example 2: if-else if-else — Grade Boundaries
When there are multiple ranges to check, use an if-else if-else chain. Java evaluates conditions top to bottom and takes the first branch that is true.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter your test score: ");
int score = input.nextInt();
if (score >= 90) {
System.out.println("Grade: 7");
} else if (score >= 80) {
System.out.println("Grade: 6");
} else if (score >= 70) {
System.out.println("Grade: 5");
} else if (score >= 60) {
System.out.println("Grade: 4");
} else if (score >= 40) {
System.out.println("Grade: 3");
} else {
System.out.println("Below passing");
}
Because conditions are checked top-to-bottom, a score of 85 reaches
score >= 90first (false), thenscore >= 80(true) — and takes that branch. The remaining conditions are never checked.
Example 3: Nested if — Finding the Smallest
An if inside another if creates a nested decision.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
if (a < b) {
if (a < c) {
System.out.println(a + " is the smallest.");
} else {
System.out.println(c + " is the smallest.");
}
} else {
if (b < c) {
System.out.println(b + " is the smallest.");
} else {
System.out.println(c + " is the smallest.");
}
}
How it works:
- First, compare
aandbto narrow down to two candidates. - Then compare the survivor with
c. - Each nested
ifmakes a further decision within the branch.
Example 4: Boolean Operators — Range Check
Combine conditions with && (AND) and || (OR) for complex decisions.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = input.nextInt();
if (age >= 13 && age <= 17) {
System.out.println("You are a teenager.");
} else if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a child.");
}
// Validation: reject out-of-range scores
System.out.print("Enter score (0-100): ");
int score = input.nextInt();
if (score < 0 || score > 100) {
System.out.println("Invalid score!");
} else {
System.out.println("Score recorded: " + score);
}
Common mistake: Writing
if (age >= 13 && <= 17)— Java requires a full condition on both sides of&&:age >= 13 && age <= 17.
Example 5: Leap Year — Compound Logic
A year is a leap year if it is divisible by 4, except centuries (divisible by 100) must also be divisible by 400.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
Testing:
- 2024 →
2024 % 4 == 0and2024 % 100 != 0→ leap year - 1900 →
1900 % 4 == 0but1900 % 100 == 0and1900 % 400 != 0→ not a leap year - 2000 →
2000 % 400 == 0→ leap year
Quick Code Check
Q1. What is printed when score = 85?
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} Q2. What is printed when x = 15?
if (x >= 10 && x <= 12) {
System.out.println("In range");
} else {
System.out.println("Out of range");
} Q3. What is printed?
boolean isRaining = true;
if (!isRaining) {
System.out.println("Go outside");
} else {
System.out.println("Stay inside");
} Q4. Which is the correct way to compare two Strings in Java?
Q5. What does age < 0 || age > 120 evaluate to when age = 150?
Trace Exercise
Trace this code — fill in the value of each variable and what is printed for the given input.
Input: score = 72, bonus = true
int score = 72;
boolean bonus = true;
String result;
if (score >= 80) {
result = "Distinction";
} else if (score >= 60) {
if (bonus) {
result = "Merit (with bonus)";
} else {
result = "Merit";
}
} else {
result = "Pass";
}
System.out.println(result);
| Check | Condition | Result |
|---|---|---|
| 1st if | score >= 80 → 72 >= 80 | |
| 1st else if | score >= 60 → 72 >= 60 | |
| Nested if | bonus |
What is printed?
Code Completion
Complete the missing parts of this program that categorises a temperature into “Hot”, “Warm”, or “Cold” using an if-else if-else chain. This exercises your understanding of how boundary values determine which branch executes.
int temp = 35;
if (temp >= ) {
System.out.println("Hot");
} (temp >= 15) {
System.out.println("Warm");
} else {
System.out.println();
} Complete the condition that checks if a number is between 1 and 100 (inclusive). This tests your ability to use the && (AND) operator to build a range check with two relational comparisons.
int num = 50;
if (num && num ) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
} Spot the Bug
This code should print “Equal” when two integers are the same, but it uses the assignment operator (=) instead of the comparison operator (==). Click the buggy line, then choose the fix.
int a = 5;
int b = 5;
if (a = b) {
System.out.println("Equal");
}What is wrong and how do you fix it?
This code should print “Match” when the String variable holds "yes", but it incorrectly uses == to compare Strings. This is one of the most common Java mistakes – Strings must be compared with .equals(), not ==. Find the bug.
String answer = "yes";
if (answer == "yes") {
System.out.println("Match");
} else {
System.out.println("No match");
}What is wrong and how do you fix it?
Output Prediction
What does this code print? This code tests your understanding of else-if chain evaluation order – remember that Java checks conditions top to bottom and executes only the first branch that is true. Type the exact output.
int x = 7;
if (x > 10) {
System.out.println("Big");
} else if (x > 5) {
System.out.println("Medium");
} else {
System.out.println("Small");
}
MediumWhat does this code print? This code demonstrates that statements after an if-else block always execute regardless of which branch was taken. Pay attention to both the conditional output and the unconditional output.
int a = 3;
int b = 5;
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
System.out.println("Done");
5
DonePractice Exercises
Core
-
Odd or even — Write a program that reads an integer and prints whether it is odd or even.
-
Largest of three — Read three integers from the user and print the largest using if-else if-else.
-
Letter grade — Read a test score (0–100) and print the corresponding IB grade (7, 6, 5, 4, 3, 2, 1) using grade boundaries.
-
Positive, negative, or zero — Read a number and print whether it is positive, negative, or zero.
Extension
- Ticket pricing — A cinema charges:
- Under 5: free
- 5–12: $8
- 13–64: $15
- 65+: $10
Read the customer’s age and print the ticket price. Validate that age is non-negative.
-
Quadrant finder — Read an (x, y) coordinate pair and print which quadrant the point is in (I, II, III, or IV), or if it lies on an axis.
- Day of the week — Read a number 1–7 and print the corresponding day name. Print “Invalid” for any other number.
Challenge
-
Triangle classifier — Read three side lengths and determine if they form a valid triangle. If valid, classify it as equilateral, isosceles, or scalene.
-
Leap year checker — Read a year from the user and determine if it is a leap year. A year is a leap year if divisible by 4, except centuries must also be divisible by 400. Print the result with an explanation.
GitHub Classroom
Connections
Prerequisites:
- Variables & Data Types — declaring variables and understanding types
Related Topics:
- Iteration (Loops) — conditions are used in loop headers
What’s Next:
- Iteration — the next construct to learn
- Loops use the same boolean conditions you learned here
Selection and iteration together give you the power to make any decision and repeat any action. Combined with sequence, these three constructs can express any algorithm.