When you have many exact values
When you compare one variable against many exact values, switch is cleaner than a long else if chain:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int day = sc.nextInt();
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("Some other day");
}
}
}Input (what the user types)
2
Output
Tuesday
- Each
caseis one possible value. breakmeans “stop here and leave the switch”.defaultruns when no case matches (likeelse).
Forgetting break
Without break, Java keeps running into the next cases. This is called fall-through:
public class Main {
public static void main(String[] args) {
int level = 2;
switch (level) {
case 1:
System.out.println("Bronze");
case 2:
System.out.println("Silver");
case 3:
System.out.println("Gold");
}
}
}Output
Silver Gold
Sometimes fall-through is useful – several cases can share the same code:
public class Main {
public static void main(String[] args) {
String fruit = "mango";
switch (fruit) {
case "apple":
case "mango":
case "banana":
System.out.println(fruit + " is a fruit");
break;
case "carrot":
System.out.println(fruit + " is a vegetable");
break;
default:
System.out.println("I don't know " + fruit);
}
}
}Output
mango is a fruit
Remember:
switchworks withint,char,Stringand enums – but not withdoubleorboolean.