Wednesday, November 16, 2011

Switch expression

Tip: A switch expression must evaluate to a char, byte, short, int, enum.

Lets put some code together and test this statement.
class SwitchTest {
 static final String ONE = "ONE";
 static final String TWO = "TWO";
 static final String THREE = "THREE";
 
 public static void testSwitch (String number) {
  switch (number) { // compilation error here
   case ONE:
    System.out.println(ONE);
    break;
   case TWO:
    System.out.println(ONE);
    break;
   case THREE:
    System.out.println(ONE);
    break;
   default:
    System.out.println(ONE);
  }
 }
 
 public static void main(String[] args) {
  testSwitch(TWO);
 }
}
If you try to compile and run the above code you will get the compilation error.

Now change data type of number from String to a char, byte, short, int, enum type and it will compile and run just fine.

Available in Android Market

No comments:

Post a Comment