Skip to content
Educora
Beginner15 min4 / 18

Conditions and switch

Teach your program to make decisions: comparison and logical operators, if/else, the ternary operator, switch and switch expressions.

Check yourself
In this lesson you will learn
  • Write conditions with comparison and logical operators
  • Use if, else if, else and the ternary operator
  • Tell the classic switch statement from the modern switch expression

If it is cold, wear a jacket; if it is raining, take an umbrella. We make decisions based on conditions every day. Programs do the same: a cash machine gives out money only when the PIN is correct, and a game ends when your lives drop to zero. In this lesson you will teach a Java program to make decisions.

Comparison and logical operators

A condition always produces a boolean value: true or false. We build conditions with comparison operators and combine several of them with logical operators.

OperatorMeaningExampleResult
==equal toage == 15true
!=not equal toage != 15false
< >less than, greater thanage > 18false
<= >=less or equal, greater or equalage >= 12true
&&AND: both conditions are trueage > 10 && age < 18true
||OR: at least one condition is trueage < 6 || age > 65false
!NOT: flips the result!(age == 15)false
In the examples, age = 15.
Java
public class Main {
    public static void main(String[] args) {
        int age = 15;
        boolean hasTicket = true;
        System.out.println(age >= 12 && hasTicket);
        System.out.println(age < 12 || !hasTicket);
        System.out.println(age == 15);
        System.out.println(age != 15);
        if (hasTicket && age >= 12) {
            System.out.println("Welcome to the film!");
        } else {
            System.out.println("Sorry, no entry.");
        }
    }
}
Expected output
true
false
true
false
Welcome to the film!
Interactive
Loading simulation…
&& works like an AND gate: the output is true (1) only when both inputs are true. Toggle the inputs and check the truth table.

if, else if and else

After the if keyword comes a condition in parentheses and then, in curly braces, the code that runs when the condition is true. else if checks the next condition, and else runs when none of the conditions hold. Java checks the conditions from top to bottom and runs the block of the first true one — the rest are skipped.

Java
public class Main {
    public static void main(String[] args) {
        int score = 78;
        if (score >= 90) {
            System.out.println("Excellent");
        } else if (score >= 70) {
            System.out.println("Good");
        } else if (score >= 50) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
        String result = score >= 50 ? "passed" : "failed";
        System.out.println("The test is " + result);
    }
}
Expected output
Good
The test is passed

78 is greater than both 70 and 50, but only “Good” was printed, because the first true condition was score >= 70. The last lines use the ternary operator: condition ? A : B. If the condition is true, the expression is A, otherwise B. It works as a short if/else when you just need to pick one of two values.

The classic switch

When you need to compare a variable with many specific values, you can write a switch instead of a long if/else if chain. switch works with int, char, String and enum values. In the classic form every case must end with break — otherwise execution “falls through” into the next case:

Java
public class Main {
    public static void main(String[] args) {
        int level = 2;
        switch (level) {
            case 1:
                System.out.println("Easy");
            case 2:
                System.out.println("Medium");
            case 3:
                System.out.println("Hard");
                break;
            default:
                System.out.println("Unknown level");
        }
    }
}
Expected output
Medium
Hard

level is 2, so execution starts at case 2. Because case 2 has no break, the program continues into case 3 and prints “Hard” as well. Only break leaves the switch. The default block runs when no case matches.

Switch expressions

Since Java 14, switch can also be written as an expression: it produces a value that you can assign straight to a variable. Arrow cases -> never fall through and need no break, and one case can list several values separated by commas. When you need a whole block, you return the value with yield.

Java
public class Main {
    public static void main(String[] args) {
        String day = "SAT";
        String type = switch (day) {
            case "SAT", "SUN" -> "weekend";
            case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
            default -> "unknown";
        };
        System.out.println(day + " is a " + type);
        int month = 2;
        int year = 2028;
        int days = switch (month) {
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
                boolean leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
                yield leap ? 29 : 28;
            }
            default -> 31;
        };
        System.out.println("Days in month " + month + ": " + days);
    }
}
Expected output
SAT is a weekend
Days in month 2: 29
2028 is a leap year, so February has 29 days.

Key points

  • A condition gives a boolean; comparisons use ==, !=, <, >, <=, >=.
  • && (AND), || (OR) and ! (NOT) combine conditions; Java skips the part that cannot change the result.
  • In an if / else if / else chain only the block of the first true condition runs.
  • The ternary operator condition ? A : B picks one of two values.
  • In a classic switch a missing break lets execution fall into the next case; a switch expression with -> returns a value and never falls through.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
If age = 15, what is age > 10 && age < 14?