After reading some of the SCJP certification last night, I got thinking about switch statements and how the expressions are evaluated, and I'm a little puzzled by something.
Java won't let you switch on a boolean, so the following will not compile :
public static void switchOnBoolean(boolean theBool)
{
System.out.println("\n\nAssessing boolean :" + theBool);
// line below won't compile, since booleans are not valid for the switch statement
switch(theBool)
{
case true:
{
System.out.println("The boolean was true");
break;
}
case false:
{
System.out.println("The boolean was false");
}
}
}
However, the compiler will not complain if you attempt to use an expression that evaluates to a boolean value in a case block, such as :
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't ever get into the case ('c' | 'd')
since it would presumably evaluate to a boolean...
So my question is:
('c' | 'd')
?'c' | 'd'
wont return boolean. In this case |
is bitwise OR not boolean OR.
You can see it in this example how it is calculated
System.out.println(Integer.toBinaryString('c'));
System.out.println(Integer.toBinaryString('d'));
System.out.println("=======");
System.out.println(Integer.toBinaryString('c' | 'd'));
Output
1100011
1100100
=======
1100111
and binary 1100111 is equal to 103 decimal integer so it is valid case argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With