Could you please let me know why do we need switch-case statement in java if we already have if-else if-else statements.
Is there any performance advantage for switch-case statements?
Could you please let me know why do we need switch-case statement in java if we already have if-else if-else statements.
Is there any performance advantage for switch-case statements?
Switch statements simplify long lists of if else blocks, improving readability. Plus they allow for fall-through cases.
Consider the following:
String str = "cat"
switch(str){
case "cat":
System.out.println("meow");
break;
case "dog":
System.out.println("woof");
break;
case "horse":
case "zebra": //fall through
System.out.println("neigh");
break;
case "lion":
case "tiger":
case "bear":
System.out.println("oh my!");
break;
case "bee":
System.out.print("buzz ");
case "fly":
System.out.println("buzz"); //fly will say "buzz" and bee will say "buzz buzz"
break;
default:
System.out.println("animal noise");
}
Now lets try to write it as if-elses
String str = "cat"
if(str.equals("cat")){
System.out.println("meow");
}
else if(str.equals("dog")){
System.out.println("woof");
}
else if(str.equals("horse") || str.equals("zebra")){
System.out.println("neigh");
} else if...
You get the point. Particularly where the switch shines is with the bee and fly. The logic there would be difficult to capture as concisely, especially if they share more than just a print statement.