What is the difference between the 'bit-wise AND' and the 'conditional AND' operators?

The & and | operators are defined for two integer operands or two boolean operands. The && and || operators are not defined for anything but two boolean operands. For all other operand types and combinations, a compile-time error shall occur.

The Integer Type Operands

The & operator is the "bit-wise AND" operator and | is the "bit-wise OR" operator.  This permits you to manipulate individual bits in a number.

The Boolean Type Operands

The && is the "conditional AND" operator and  || is the "conditional OR" operator. The && and || operators are evaluated in short circuit fashion. This means that when you have an expression like:

e1 && e2

if expression e1 evaluates to be false, then the value of the expression e2 is not calculated. Similarly, if e1 evaluates to be true, then the value of e1 || e2 is automatically true, and therefore e2 is not evaluated.

For example, in the expression

x != 0 && 1 / x > x + y // no division by 0

the second part is never evaluated if x equals zero. Thus, 1/x is not computed if x is zero, and no divide-by-zero error can occur.

The & the (unconditional) "logical AND" operator and  | is the (unconditional)"logical OR" operator. When applied to boolean values, the & and | operators yield a boolean value. These operators are similar to the && and || operators, except that the & and | operators are not evaluated in "short-circuit" fashion. That is, both operands are first evaluated before computing the result.

For example

class Program {
public static void main(String [] args){
boolean[] b = new boolean[3];
int count = 0;
b[0] = false;
b[1] = false;
b[2] = false;

//The first operand evaluates to false,
//the evaluation of the second operand is skipped.
//Therefor, the count does not add 1.
if (false && b[++count]) {
System.out.println("True -- 1");
else {
System.out.println("False -- 1");

//Both operands are evaluated. Therefor, the count adds 1
if (false & b[++count]) {
System.out.println("True -- 2");
else {
System.out.println("False -- 2");

The output result is

False -- 1
False -- 2

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |