After reading some SCJP certificates last night, I thought about switch statements and how expressions are evaluated, and I'm a little puzzled by something.
Java will not allow you to include a boolean, so the following will not compile:
public static void switchOnBoolean(boolean theBool) { System.out.println("\n\nAssessing boolean :" + theBool);
However, the compiler will not complain if you try to use an expression that evaluates a boolean value in a case block, for example:
public static void switchOnChar(char theChar) { System.out.println("\n\nAssessing char : " + theChar); switch(theChar) { case 'a': { System.out.println("The char was a"); break; } case 'b': { System.out.println("The char was b"); break; } case ('c' | 'd'): { System.out.println("The char was c or d"); break; } default: { System.out.println("The char didn't match anything, must be something else"); } } }
Ultimately, I can never enter the case ('c' | 'd') , as he would presumably appreciate the logical ...
So my question is:
- Why is it legal to use something like
('c' | 'd') ? - How could this ever be useful, as that would be unattainable.
- If you've ever wanted to deal with multiple values, but without using a default value, is this your only choice for re-implementation as an if-else statement?
Jimmy source share