I earned my second “Nice Answer” badge on a Stack Overflow question. I, myself, don’t find using switch all that useful. The syntax for switches are always harder to remember compared to chaining a bunch of if else statements. There are just a few times when switches do come in handy such as finding the number of days in a month. The answer was well received because it is written in a syntax familiar to all C-like languages.
Answer:
There are a few cases where switch is more readable and comes in handy. Usually when you have grouping of options.
Here is one of them:
int numDays = 0;
int month = 2;
int year = 2010;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
}


