Sunday, January 8, 2017

Difference between Bitwsie and Logical Operator in Java - & vs &&, | vs ||

Java beginners often ask the same type of questions, and of them is what is difference between & and && operator in Java or difference between | and || operators? The standard answer of this question is well, the main difference between & and && is that 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, 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 e.g. 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.

And, If you are new to Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.




& vs && and | vs || in Java

Let's first see examples of bitwise AND operator, 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 variable 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 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 || operator 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 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 address is not null, but as soon as address becomes null, 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 null check is another way to avoid NullPointerException in Java. Always use && instead of & if you don't want to check 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.

Difference between & and && in Java








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 result is determined. In the best case, a short-circuit operators can return result by just executing one condition and in the worst case by executing all conditions.


3) && and & is also known as conditional and unconditional AND operators 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.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

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

1 comment :

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)

Post a Comment