Java; Logical, Bitwise and Short-circuit Operators

Jean Villete
3 min readJun 12, 2018

--

#Logical Operators (also bitwise)

The logical operators are binary ones and may be applied to both numeric and boolean data types. When applied on boolean data types it’s known as logical operators, but if numeric variables/values are involved, so it’s known as bitwise operators;

& (and)
| (inclusive or)
^ (exclusive or)

Considering boolean values, these (logical) operators evaluates both left and right-hand-side of an expression, which as expected, results on another boolean value, e.g;

true & true -> true
true & false -> false
false & false -> false
false & true -> false

true | true -> true
true | false -> true
false | false -> false
false | true -> true

true ^ true -> false
true ^ false -> true
false ^ false -> false
false ^ true -> true

Note 1: It is not possible apply logical operators on boolean and numeric data types at the same time, in other words, the operands must be both (left and right-hand-side) boolean (logical operators) or numeric (bitwise operators).

Note 2: The return of a logical operator (only possible with boolean data type) expression is always a boolean result.

Note 3: The return of a bitwise operator (only possible with numeric data type) expression, follows the same promotion data type rules as for arithmetic expressions, i.e;
#1 - if two operands with different data type are involved, the smaller one is promoted to same data type as the larger one.
#2 - smaller data type (byte and short) are always promoted to int data type, even if there’re only smaller data type involved on the expression.
#3 - if one operand is a numeric integral and the other is a floating point number, so the numeric integral one is promoted to the same floating point data type, before apply the operator.
#4 - the result is the same as of the larger operand data type.

#Short-circuit Operators

Short-circuit operators, are logical operators (they can only be applied on boolean operands) that might not evaluate the right-hand-side operand, cause the left-hand-side gives a clue that tells the other hand-side doesn’t need to be evaluated, e.g;

if ( referenceVariable != null && referenceVariable.getValue() > 0 )
/*
* The referenceVariable.getValue() would throw an NullPointerException in case the referenceVariable is null, so the getValue() will only be executed in case the referenceVariable is not null.
*
* If the short-circuit was not used here and the variable referenceVariable was null, so surely a NullPointerException would be thrown.
*/

Short-circuits result the same values as those on non short-circuit respective operators, and the short-circuit symbols are;

&& (and)
|| (inclusive or)

Note: There’s no a short-circuit operator (shortcut) for “exclusive or”, and it does make sense, cause always both left and right-hand-side have to be evaluated.

That’s it for now!

--

--