0

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?

Rajesh
  • 39
  • 4
  • They are fairly different things when you think about it. (Spoiler alert: internally there are even two different switch-case constructs in the JVM.) – biziclop May 24 '17 at 17:52
  • What's wrong with having both? What's wrong with having four loop constructs? What's wrong with having many different assignment operators? What's wrong with having both lambdas and anonymous classes? NOTHING. What computer languages do you know of that _don't_ provide different ways to express an algorithm for the sake of clarity and ease of maintenance? – Lew Bloch May 24 '17 at 18:14
  • Why can we multiply numbers when we already have addition which can do the same thing? – takendarkk May 24 '17 at 18:51

1 Answers1

1

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.

Yonah Karp
  • 581
  • 7
  • 22