Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 4 of 20 · 6 min read

Java decisions: if, else and switch

Java if-else and switch notes with examples: else-if ladders, nested if, logical conditions, the classic switch and the switch expression with yield.

Why decisions?

Programs must choose: pass or fail, valid PIN or not, which menu option. Java chooses with if and switch. Each test is a boolean condition: something that is true or false.

if

int marks = 72;
if (marks >= 40) {
    System.out.println("Pass");
}

The block runs only when the condition is true. The brackets around the condition are required.

if-else

int age = 16;
if (age >= 18) {
    System.out.println("You can vote");
} else {
    System.out.println("Wait " + (18 - age) + " more years");
}

else-if ladder

Java checks the conditions from top to bottom and runs the first one that is true:

int marks = 83;
char grade;
if (marks >= 90) {
    grade = 'A';
} else if (marks >= 75) {
    grade = 'B';
} else if (marks >= 60) {
    grade = 'C';
} else if (marks >= 40) {
    grade = 'D';
} else {
    grade = 'F';
}
System.out.println("Grade: " + grade);   // Grade: B

Order matters. If marks >= 40 came first, every passing student would get a D.

Nested if

An if inside another if:

boolean hasCard = true;
int pin = 4321;
if (hasCard) {
    if (pin == 4321) {
        System.out.println("Welcome");
    } else {
        System.out.println("Wrong PIN");
    }
} else {
    System.out.println("Insert your card");
}

Combining conditions

Use && (and), || (or) and ! (not):

int age = 20;
boolean hasLicence = true;
if (age >= 18 && hasLicence) {
    System.out.println("You may drive");
}

char day = 'S';
if (day == 'S' || day == 'U') {
    System.out.println("Weekend");
}

Leap year

A year is a leap year if it is divisible by 4 and not by 100, or if it is divisible by 400:

int y = 2024;
boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
System.out.println(y + (leap ? " is" : " is not") + " a leap year");

The classic switch

switch compares one value against many fixed cases. It works with int, char, String, enums and their wrappers.

int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Another day");
}

Fall-through

Without break, execution continues into the next case. That is usually a bug, but you can use it on purpose to group cases:

char ch = 'e';
switch (ch) {
    case 'a': case 'e': case 'i': case 'o': case 'u':
        System.out.println("Vowel");
        break;
    default:
        System.out.println("Consonant");
}

The switch expression (Java 14+)

The arrow form has no fall-through, needs no break, and can return a value:

String day = "SAT";
String type = switch (day) {
    case "SAT", "SUN" -> "Weekend";
    case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
    default -> "Unknown";
};
System.out.println(type);   // Weekend

When a case needs several statements, use a block and yield the value:

int units = 250;
double bill = switch (units / 100) {
    case 0 -> units * 3.0;
    case 1 -> units * 4.5;
    default -> {
        double base = units * 6.0;
        yield base + 50;       // fixed charge for heavy users
    }
};

if or switch?

  • Use if for ranges and complex conditions (marks >= 75, age > 18 && hasId).
  • Use switch when one variable is compared against fixed values (menu choices, day names).

Example: a calculator menu

import java.util.Scanner;

public class Calc {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double a = sc.nextDouble();
        char op = sc.next().charAt(0);
        double b = sc.nextDouble();
        double result = switch (op) {
            case '+' -> a + b;
            case '-' -> a - b;
            case '*' -> a * b;
            case '/' -> b != 0 ? a / b : Double.NaN;
            default -> {
                System.out.println("Unknown operator");
                yield 0;
            }
        };
        System.out.println("Result: " + result);
    }
}

Common mistakes

  • Putting a semicolon after the condition: if (x > 5); ends the if there, so the block always runs.
  • Using = instead of ==: if (x = 5) does not compile for an int.
  • Forgetting break in a classic switch and running into the next case.
  • Comparing strings with == in an if; use .equals(). (switch on a String is safe.)
  • Leaving out braces and adding a second line later: only the first line belongs to the if.

Key points

  • if, else if and else run the first block whose condition is true.
  • Combine conditions with &&, || and !.
  • The classic switch needs break to stop fall-through.
  • The arrow switch expression returns a value, has no fall-through, and uses yield inside a block.
  • Ranges go in if; fixed values suit switch.

Practice questions

1. What does this print? int x = 5; if (x > 2) if (x > 8) System.out.println("A"); else System.out.println("B");

B. An else belongs to the nearest unmatched if, here if (x > 8), which is false.

2. Write an if-else ladder that prints "Child" (under 13), "Teen" (13 to 19) or "Adult".
if (age < 13) {
    System.out.println("Child");
} else if (age <= 19) {
    System.out.println("Teen");
} else {
    System.out.println("Adult");
}
3. What is printed when n = 2? switch (n) { case 1: System.out.print("one "); case 2: System.out.print("two "); case 3: System.out.print("three "); }

two three . There is no break, so case 2 falls through into case 3.

4. Rewrite this as a switch expression: month 12, 1 or 2 is "Winter", 6 to 9 is "Monsoon", anything else is "Other".
String season = switch (month) {
    case 12, 1, 2 -> "Winter";
    case 6, 7, 8, 9 -> "Monsoon";
    default -> "Other";
};
5. Write a condition that is true when a number n is between 1 and 100 inclusive and is a multiple of 7.
boolean ok = n >= 1 && n <= 100 && n % 7 == 0;