Exercises · Q8
Q.When is a switch statement preferable to an if...else if ladder? Rewrite the following as a switch:
if (choice == 1) System.out.println("Add");
else if (choice == 2) System.out.println("Subtract");
else System.out.println("Invalid");
if (choice == 1) System.out.println("Add");
else if (choice == 2) System.out.println("Subtract");
else System.out.println("Invalid");
ChseodishaTextbookSubjectiveImportance★★★★★est
62% · 8/13 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →When to prefer switch. An if...else if ladder can test any conditions (ranges, combinations, different variables). But when the logic is simply "compare one variable against several fixed constant values", a switch is cleaner and easier to read, because the variable is written once and each possible value is a labelled case.
Rewritten as a switch:
switch (choice) {
case 1:
System.out.println("Add");
break;
case 2:
System.out.println("Subtract");
break;
default:
System.out.println("Invalid");
}
Points to note:
- Each
casegives one value ofchoiceto match. breakis essential at the end of each case; it makes control leave the switch. Withoutbreak, execution "falls through" into the next case and runs its code too. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.