Why is a boolean expression valid in a case block when boolean types are not supported by data types for switches?

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); // 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 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?
+6
source share
4 answers

'c' | 'd' 'c' | 'd' wont return boolean. In this case | bitwise OR not logical OR.

In this example, you can see 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')); 

Exit

 1100011 1100100 ======= 1100111 

and binary 1100111 is 103 decimal integers, so it is an argument to the case argument.

+12
source

'c' | 'd' 'c' | 'd' is bitwise or leads to 'g' , therefore it is valid on the switch.

You can match more than one case without going to an if-statement, for example

 switch(theChar) { case 'a': break; case 'b': break; case 'c': case 'd': System.out.println("c or d"); break; default: throw new IllegalStateException(); } 
+6
source
 ('c' | 'd') 

bitwise, or so it will not return a boolean value, it is completely valid.

If you try it like this:

 System.out.println('c' | 'd'); 

it will print 103, which is the ASCII code for g .

+4
source

If you run 'c' || 'd' 'c' || 'd' , you will get the expected logical error and will not compile.

'c' | 'd' 'c' | 'd' bitwise OR

+1
source

Source: https://habr.com/ru/post/922351/


All Articles