Convert the following if else if construct into switch case: if(var == 1) System.out.println("good"); else if(var == 2) System.out.println("better"); else if(var == 3) System.out.println("best"); else System.out.println("invalid");
Topic: if-else-if to switch
Answer
switch(var) { case 1: System.out.println("good"); break;
case 2: System.out.println("better"); break;
case 3: System.out.println("best"); break;
default: System.out.println("invalid"); }
The conversion is direct because every test is an equality against a constant — which is the only kind of test a switch can perform. Each condition becomes a case label, and the final else becomes default. The break after each case is essential. Without it, execution falls through into the case below and several messages would be printed — the single most common error in switch questions. The default needs no break, being last. Note that a construct such as if(var > 1) could NOT be converted, since a case label cannot express a range.