Reading history

Java if-else and switch Statements (With Examples)

4 min read 0 views

Learn Java decision making: if, else if and else chains, combining conditions, classic switch with break, and modern switch expressions.

Decision-making code lets a program respond to its data: give a grade from the marks, allow entry only with a ticket, set a price by size. Java offers if, else if and else for range checks, and switch for picking among fixed values. Modern Java (14+) also has switch expressions with arrow syntax, which are shorter and safer.

In this lesson you will learn

  • How an if / else if / else chain is checked
  • How to combine conditions
  • The classic switch statement and why break matters
  • Switch expressions with ->
  • When to choose if or switch

if, else if and else

public class Main {
    public static void main(String[] args) {
        int marks = 76;
        String grade;
        if (marks >= 80) {
            grade = "A+";
        } else if (marks >= 70) {
            grade = "A";
        } else if (marks >= 60) {
            grade = "A-";
        } else if (marks >= 33) {
            grade = "Pass";
        } else {
            grade = "Fail";
        }
        System.out.println("Marks " + marks + " -> " + grade);

        int age = 19;
        boolean hasId = true;
        if (age >= 18 && hasId) {
            System.out.println("Can vote");
        }
    }
}

Output

Marks 76 -> A
Can vote
  • Conditions must be in brackets and must be boolean. Java does not treat 0 or an empty string as false.
  • Java checks each condition in turn and runs only the first block whose condition is true. Marks of 76 fail >= 80 and pass >= 70, so the grade is “A”.
  • Curly braces mark each block. They are optional for a single statement, but always using them prevents bugs when you add lines later.
  • The compiler accepts the grade variable because every path through the chain assigns it.

switch Statements and Expressions

public class Main {
    public static void main(String[] args) {
        int day = 6;
        switch (day) {
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Weekday");
        }

        String size = "M";
        int price = switch (size) {        // switch expression (Java 14+)
            case "S" -> 250;
            case "M", "L" -> 300;
            default -> 350;
        };
        System.out.println("Price: " + price);
    }
}

Output

Friday
Price: 300
  • The classic switch jumps to the matching case. break ends it. Without break, execution “falls through” into the next case, a common bug.
  • default runs when no case matches.
  • A switch expression uses ->, never falls through, can list several values per case (case "M", "L"), and returns a value directly.
  • switch works with int, char, String and enums.

if or switch?

UseWhen
if / else ifRanges and complex conditions (marks >= 80, age >= 18 && hasId)
switchOne variable compared against several exact values (days, menu choices, sizes)

Common Mistakes

  1. Forgetting break in a classic switch.
  2. A semicolon after the condition: if (x > 5); ends the if immediately, so the block below always runs.
  3. Wrong order of ranges. Check >= 80 before >= 70, or every high mark gets the lower grade.
  4. Comparing strings with == in conditions. Use .equals() (switch on strings already does).

Practice Exercises

Exercise 1. Print whether a number is positive, negative or zero.

Show answer
int n = -4;
if (n > 0) System.out.println("Positive");
else if (n < 0) System.out.println("Negative");
else System.out.println("Zero");

Exercise 2. Use a switch expression to turn 1–3 into “Gold”, “Silver”, “Bronze”, and anything else into “None”.

Show answer
int place = 2;
String medal = switch (place) {
    case 1 -> "Gold";
    case 2 -> "Silver";
    case 3 -> "Bronze";
    default -> "None";
};
System.out.println(medal);   // Silver

Frequently Asked Questions

Can a switch use strings in Java?

Yes, since Java 7. The comparison uses equals(), so it checks the text, not the object.

Is fall-through ever useful?

Occasionally, for grouping cases. With switch expressions you can list several values in one case instead (case 6, 7 -> "Weekend"), which is clearer.

Summary

  • if / else if / else runs the first true branch.
  • Conditions must be boolean; always use braces.
  • Classic switch needs break; switch expressions with -> do not.
  • Use if for ranges and switch for exact values.

Next: Java Loops.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *