Switch vs if else in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Switch vs if else in Java

I can't notice any difference performance between using if else and switch, which is better?

3rd Jun 2017, 1:04 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
3 Answers
+ 9
switch and if/else are different in that if/else can check any condition, while switch can only check for one variable against single values. In terms of performance, they are similar. Use switch for when you need to check something specific a variable contains. This is useful when a variable has a long name, because you only have to type it once. Ex: switch (grade) { case "A": case "a": //your code break; //more cases & default } if/else lets you check any sort of condition you want - if a variable is in a range, checking multiple variables, checking what a method returns, or anything that evaluates as true/false. Ex: if (gpa <= 4.0 && gpa >= 3.5) { //your code } //more else/ifs and else
3rd Jun 2017, 1:25 AM
Tamra
Tamra - avatar
+ 1
Switch checks values while if-else checks conditions. So if you want to simply fork flow by value, switch is better. I show you just an example where switch looks fine. (For simplicity, this code doesn't take leap years into account) public int dayOfMonth(int month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return 28; default: return 0; // or throw exception }
3rd Jun 2017, 2:33 AM
Twelfty
Twelfty - avatar