R
Rishtaara
Java Fundamentals
Lesson 7 of 36Article15 min

Switch & While Loop

switch checks one variable against many cases. break stops fall-through to the next case.

Switch — many options, one value

switch checks one variable against many cases. break stops fall-through to the next case.

Good for menu choices, day-of-week, status codes. Java 14+ supports switch expressions too.

Real-life example: A vending machine — you press B3 (case), it gives chips (break). Without break, it might give chips AND soda.

Switch statement
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("Other day");
}

While — repeat while condition is true

while (condition) { ... } checks condition before each loop. If false at start, body never runs.

Watch for infinite loops — condition must eventually become false.

Real-life example: While there are dishes in the sink, keep washing. When sink is empty, stop.

While loop
int i = 1;
while (i <= 5) {
    System.out.println("Count: " + i);
    i++;
}
// Prints Count: 1 through 5