Selection (if/else)

B2.3.2 - Construct programs utilizing appropriate selection structures.


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

Python note: this trap is Java-specific. In Python, == compares string content, so if name == "Alice": is correct. Python also spells the boolean operators as words: and, or, not instead of &&, ||, !.


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");
}
score = int(input("Enter your score: "))

if score >= 50:
    print("Pass")
else:
    print("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");
}
score = int(input("Enter your test score: "))

if score >= 90:
    print("Grade: 7")
elif score >= 80:
    print("Grade: 6")
elif score >= 70:
    print("Grade: 5")
elif score >= 60:
    print("Grade: 4")
elif score >= 40:
    print("Grade: 3")
else:
    print("Below passing")

Because conditions are checked top-to-bottom, a score of 85 reaches score >= 90 first (false), then score >= 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.");
    }
}
# split() breaks one input line into pieces - IB's named tool for this
values = input("Enter three numbers: ").split()
a = int(values[0])
b = int(values[1])
c = int(values[2])

if a < b:
    if a < c:
        print(a, "is the smallest.")
    else:
        print(c, "is the smallest.")
else:
    if b < c:
        print(b, "is the smallest.")
    else:
        print(c, "is the smallest.")

How it works:

  • First, compare a and b to narrow down to two candidates.
  • Then compare the survivor with c.
  • Each nested if makes 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.");
}
age = int(input("Enter your age: "))

if age >= 13 and age <= 17:
    print("You are a teenager.")
elif age >= 18:
    print("You are an adult.")
else:
    print("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);
}
# Validation: reject out-of-range scores
score = int(input("Enter score (0-100): "))

if score < 0 or score > 100:
    print("Invalid score!")
else:
    print("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.");
}
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")

Testing:

  • 2024 → 2024 % 4 == 0 and 2024 % 100 != 0 → leap year
  • 1900 → 1900 % 4 == 0 but 1900 % 100 == 0 and 1900 % 400 != 0 → not a leap year
  • 2000 → 2000 % 400 == 0 → leap year

Quick 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");
}
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("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");
}
if x >= 10 and x <= 12:
    print("In range")
else:
    print("Out of range")

Q3. What is printed?

boolean isRaining = true;
if (!isRaining) {
    System.out.println("Go outside");
} else {
    System.out.println("Stay inside");
}
is_raining = True
if not is_raining:
    print("Go outside")
else:
    print("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);
score = 72
bonus = True
result = ""

if score >= 80:
    result = "Distinction"
elif score >= 60:
    if bonus == True:
        result = "Merit (with bonus)"
    else:
        result = "Merit"
else:
    result = "Pass"

print(result)
CheckConditionResult
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 using an if-else if-else chain: “Hot” for 30 or above, “Warm” for 15 to 29, and “Cold” for anything lower. 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 Error

This code should print “Equal” when two integers are the same, but it uses the assignment operator (=) instead of the comparison operator (==). Select 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 ==. (With two literals in the same file, as here, this happens to print Match, because Java reuses identical literals; with a word the user types it prints No match. Either way == is the wrong test.) 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?


Predict the Output

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");
}
x = 7
if x > 10:
    print("Big")
elif x > 5:
    print("Medium")
else:
    print("Small")
Expected: Medium

What 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");
a = 3
b = 5
if a > b:
    print(a)
else:
    print(b)
print("Done")
Expected: 5
Done

Practice Exercises

Core

  1. Odd or even - Write a program that reads an integer and prints whether it is odd or even.

  2. Largest of three - Read three integers from the user and print the largest using if-else if-else.

  3. Letter grade - Read a test score (0-100) and print the corresponding IB grade (7, 6, 5, 4, 3, 2, 1) using grade boundaries.

  4. Positive, negative, or zero - Read a number and print whether it is positive, negative, or zero.

Extension

  1. 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.

  2. 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.

  3. Day of the week - Read a number 1-7 and print the corresponding day name. Print “Invalid” for any other number.

Challenge

  1. Triangle classifier - Read three side lengths and determine if they form a valid triangle. If valid, classify it as equilateral, isosceles, or scalene.

  2. 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

Java Selection
Practice if/else, nested conditions, and boolean logic.

A class assignment on GitHub Classroom: use it when your teacher has set it. It needs a free GitHub account.

Working in the Codespace

  1. Accept and open. Accept the assignment above, open the link in the email from GitHub, then press Open in Codespace. In Java, change the status bar from Lightweight to Standard mode.
  2. Write and check. Open src/Selection.java and complete each TODO. Press Run and compare the output with the comments, or run bash run-tests.sh in the Terminal.
  3. Submit. In Source Control, write a message, press Commit, then Sync Changes. Your teacher’s feedback arrives as a pull request called Feedback.

The full Codespace guide, with pictures


Connections

Prerequisites:

Related Topics:

Where this leads:

  • 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.