How would you rewrite this using a switch statement?

Given this method: Java

String checkZero(int x)
{
String s;
if (x == 0)
s = "zero";
else
s = "non-zero";
return s;
}

1. How would you rewrite this using a switch statement?

2. Which do you think is the best choice for this method? Why?

Sídhe2010-11-09T16:12:06Z

Favorite Answer

String s;
switch (x) {
case 0: s = "zero"; break;
default: s="non-zero";
}
return s;


2. If-else is better in this case. Swtich is better when the alternative would be if-else if-else if-else if-else if-else if-else if-else (that is, a LOT of cases)