Are short circuit operators overloaded?

There are two cases of using the bitwise operator:

For booleans

boolean a = true; boolean b= false; boolean c = a|b; // Giving response after logical OR for booleans. 

For whole

 int a = 10; int b = 20; int c = a|b; // Giving response after bitwise OR for boolean equivalents of "a" and "b". 

Both of the above cases correspond to http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2 .

Is the operator overloaded | ?

I just want to ask a very simple question: "|" is overloaded or performs the same bitwise OR task for both logical elements (binary equivalents, of course) and integer?

+4
source share
2 answers

You can find the answer here :

When both operands are a &, ^ or | the operators are of type boolean or Boolean, then the type of the bitwise expression of the operator is logical. In all cases, the operands are subject to decompression of the transform (ยง5.1.8) if necessary.

If you use the operator | to boolean , then the result will be similar to using || but note that the difference is as follows:

 boolean a = true, b = false; boolean c = a | b; //b will still be evaluated c = a || b; //b will not be evaluated 

I'm not sure what it means if it is overloaded, because since it can be used for different types, it is overloaded.

+4
source

I'm not quite sure what you are asking, but at least the bytecode is different from boolean c = a|b and boolean c = a||b :

 boolean a = true; boolean b = false; 
 boolean c = a|b; ILOAD 1 ILOAD 2 IOR ISTORE 3 
 boolean c = a||b; ILOAD 1 IFNE L4 ILOAD 2 IFNE L4 ICONST_0 

Thus, two operators effectively lead to different operations at the bytecode level. In particular, || evaluates only the second operand if the first operand is false and | evaluates both operands anyway:

 public boolean a() { System.out.println(" a"); return true; } public boolean b() { System.out.println(" b"); return false; } public void c() { System.out.println("a() | b()"); boolean r1 = a() | b(); System.out.println("\na() || b()"); boolean r2 = a() || b(); } 

Output:

 a() | b() a b a() || b() a 

At the same time, the bytecode for the integer bitwise or the same as for Boolean bitwise or:

 int a1 = 10; int a2 = 20; int c1 = a1 | a2; 
 ILOAD 4 ILOAD 5 IOR ISTORE 6 
+2
source

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


All Articles