4

I am going through SCJP 6 book by Kathy and Bret and came across some text from this book, chapter 4 (operators)

Because you know by now that Java is not C++, you won't be surprised that Java operators aren't typically overloaded. There are, however, a few exceptional operators that come overloaded:

  • The + operator can be used to add two numeric primitives together, or to perform a concatenation operation if either operand is a String.
  • The &, |, and ^ operators can all be used in two different ways, although as of this version of the exam, their bit-twiddling capabilities won't be tested.

I am failing to understand the second use of &, | and ^ operators in java other than bitwise AND, OR and XOR respectively. What are the two different ways of using & operator in java?

love gupta
  • 440
  • 5
  • 11

1 Answers1

4

& can be applied on two boolean operands as a non short circuiting version of binary AND operator (unlike the short circuiting && operator).

| can be applied on two boolean operands as a non short circuiting version of binary OR operator (unlike the short circuiting || operator).

^ (XOR) can also be applied on two boolean operands.

To summarize, all 3 operators can serve as boolean operators (when applied to boolean operands) or bit-wise operators (when applies to integer operands).

These operators are described in JLS 15.22.2.:

15.22.2. Boolean Logical Operators &, ^, and |

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

  • For &, the result value is true if both operand values are true; otherwise, the result is false.

  • For ^, the result value is true if the operand values are different; otherwise, the result is false.

  • For |, the result value is false if both operand values are false; otherwise, the result is true.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768