Difference between Bitwise and Logical AND, OR Operators in Java? Examples

Java beginners often ask the same type of questions, and of them is what is the difference between & and && operator in Java or the difference between | and || operators? The standard answer to this question is well, the main difference between & and && is that the former is a bitwise operator, and && is a logical operator in Java. That's academic until you clearly explain the difference in working of & and && or | and ||. For absolute beginners, & is used to represent AND logic operation in Java and | is used to represent OR logic operation.

If we use only one & or | then it's known as “bitwise AND” and bitwise OR operators and if we use double && or || then it's known as logical or short-circuit AND and OR operators. From the name, you can guess bitwise operates at the bit level and perform AND logical operation to each bit, while logical operators operate on boolean variables only.

The main difference lies in their short circuit behavior, which means if there are two or more conditions, which are joined using && or || operator then not all conditions are tested as soon as you have enough data to determine the result.

For example in the case of AND operation involving multiple conditions, the rest are not checked as soon as one of them becomes false, because the result will always be false.

Similarly, in the case of OR short circuit operator ||, remaining conditions are not executed if one of them is true, because as soon as one operand becomes true, the result of the operation will be true, regardless of the result of the remaining condition.

This short circuit nature is another reason, why logical operators are also known as short-circuit operators. In order to solve programming problems like how to count the number of set bits or 1s on Integer, a good understanding of the bitwise operator is required. I think we have enough theory, let's see some real examples.




The & vs && and | vs || in Java

Let's first see examples of bitwise AND operators, as I said they operate at the bit level and calculate AND for each bit in a number e.g. if we apply bitwise AND or & between two integer variables then there will be 32 AND operations as int is 32 bit in length. Similarly, for byte, it's 8 AND conditions and for short variables, it's 16 AND operations.

int two = -2;
int four = -4;                          

int result = two & four; // bitwise AND operation

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111100

You can clearly see that for variable result, last two bits are off i.e. zero because of AND operations on respective bits of two and four int variable i.e . 0 & 0 = 0 , 1 & 0 = 0

Similarly, if we perform a bitwise OR operation between these two variables, we will see the following result.

result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110


but using logical && and || operators on integral variables will result in compilation error.

int result = two && four; // Compilation Error

The operator && is undefined for the argument type(s) int, int


Similarly

int result = two || four; // Compilation Error

The operator || is undefined for the argument type(s) int, int


It means you can only use bitwise AND and OR operators & and | with integral types in Java. Now let's see the more interesting cases of applying AND and OR operations on boolean types. This is where many Java programmers make mistakes, as both & and && can be used with boolean variables. For example, what is the difference between the following two cases :

String address = person.getAddress();

if(address != null && address.length() > 0){
   send();
}

and

if(address != null & address.length() > 0){
   post(address);
}

This code snippet is checking if String is empty or not before calling the post() method, though there are more clever ways to check if String is empty or not, this will do for our example. You will not notice any difference if the address is not null, but as soon as the address becomes null, the second code snippet will start throwing java.lang.NullPointerException

Why? because && is short-circuit AND operator and doesn't execute address.length() if first condition is false e.g. when address is null, while & is bitwise AND operator and always execute address.length() > 0 expression, no matter whether address != null returns true or false. 

So you can now realize how & and && can make difference in your code, by the way using && for a null check is another way to avoid NullPointerException in Java. Always use && instead of & if you don't want to check the remaining conditions.



Difference between & and && in Java

It's time to revise whatever we learn so far. Also, remember that there is far more bitwise operators than we discussed here, the complete list is shown in this image, which also includes bitshift operators e.g. left shift, right shift, and right shift without a sign.

1. You can use & with both integral and boolean variables in Java, but you can use && with only boolean operands. Integral variables don't include floating-point types e.g. float and double.

2. Bitwise AND & or bitwise OR | performs a logical operation on all bits, while logical AND && and logical OR || abort executing a remaining expression, as soon as the result is determined. In the best case, short-circuit operators can return results by just executing one condition and in the worst case by executing all conditions.

3. The && and & is also known as conditional and unconditional AND operators in Java. You can further check these Java Programming courses for Beginners to learn more about bitwise operators in Java and other fundamental Java concepts. 

Difference between & and && in Java

That's all about the difference between the bitwise and logical operator in Java. Remember logical operator is also known as a short circuit operator in Java. In this tutorial, we will learn that how & and && are different and how | is different than ||.

Also, remember that logical operator is only applicable for boolean operands but bitwise operator e.g. bitwise AND, OR, XOR, and NOR can be applied to both boolean and integral type as well e.g. byte, short, char, int, and long.


Some Programming problems based on the bitwise operator :
  1. How to swap two numbers without using a temp variable? (solution)
  2. How to find if the number is even or odd? (solution)
  3. How to add two numbers without using the + operator in Java? (solution)
  4. How to check if an integer is a power of two in Java? (solution)

2 comments :

Jay said...

Operators are special symbols like '+','-','/'etc.When operators are placed between operands,can perform specific operation and give result. In (http://result.In) this post,we shall discuss about some important and mostly used operators.
1-Increment Operators(++)->This operator simply increments the vaariable by 1. Ex- int a=12; a++; // means a=a+1; When ++ operator follow variables or placed before it,it is called post increment.Ex- The above exaple. When ++ operator precede variables or placed after it,it is called pre increment.Ex- int a=13;++a;
2-Decrement Operators(--)->This operator simply… for more visitOperators in Java (https://jaysmilet.blogspot.com/2018/10/operators-in-java.html)

prashant saini said...

Suggest best book for advanced java

Post a Comment