r/javahelp • u/Fr4nkWh1te • Jul 13 '19
Are non short-circuit logical operators ( | & ) refered to as bitwise operators?
That's one thing that confuses me.
From my research online, it seems that | and & are referred to as "bitwise operators", even if they are used as logical operators between 2 boolean expressions. What do they have to do with bitwise operations, besides using the same operator symbols?
Here an example:
The non-bitwise operators && and || are short-circuit operators. In other words, with &&, if the LHS is false, the RHS will never be evaluated; with || if the LHS is true, then the RHS will never be evaluated. On the other hand, the bitwise operators & and | are non-short-circuit, and will always evaluate both the LHS and the RHS.
0
Jul 13 '19
[deleted]
6
u/marvk Jul 13 '19 edited Jul 13 '19
Unlike C, Java can not interpret numbers as booleans. Hence, if you have an expression like
if (a & b) { },aandbmust both bebooleanvariables.
&and|are operators that can be used on numbers and on booleans. If you use them on booleans, they will not short circuit.Suppose you have a method with a side effect:
boolean m() { System.out.println("I'm a side effect"); return true; }In the following example, the side effect will not be visible:
if (false && m()) { .... }while in this snippet will print
I'm a side effectto the console:if (false & m()) { .... }On operands without side effects, they will produce the same result.
2
Jul 13 '19
I think thinking of & | as non-short circuiting logic operators is flawed. Think of them as bitwise and nothing else.
1
u/marvk Jul 13 '19
They are both. There are no bitwise operations over booleans. You could think of booleans as single bit numbers, but that just complicates things IMO.
0
Jul 13 '19
[deleted]
1
u/Roachmeister Java Dev Jul 14 '19
Booleans may be internally represented as bits, but in Java they are not bits. They are
trueandfalse. Examples:int i = 0 & 1; // 0 boolean b = true & false; // false int i2 = 1 & false; // syntax error boolean b2 = true & 1; // syntax errorAs others have said, | and & are overloaded operators. With numeric types, they are bitwise operators. With booleans, they are non-shortcircuiting logical operators. This is all because Java is strongly typed.
0
u/[deleted] Jul 13 '19
[deleted]