Bitwise & vs Logical && Operators in Java

Naveen Metta
4 min readMay 17, 2024
credit goes to the owner : https://www.scaler.com/topics/c/bitwise-operators-in-c/
source : www.scaler.com

In Java, understanding the difference between bitwise & and logical && operators is crucial for writing efficient and correct code. These operators, while sometimes appearing similar, serve different purposes and are used in different contexts. This article provides a comprehensive explanation of both operators, along with ample code examples to illustrate their usage.

Bitwise & Operator

Definition

The bitwise & (AND) operator performs a binary AND operation between corresponding bits of two integers. Each bit in the result is set to 1 if and only if the corresponding bits in both operands are 1.

Syntax

int result = a & b;

Example

public class BitwiseANDExample {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // result: 0001 (decimal: 1)
System.out.println("Bitwise AND of " + a + " and " + b + " is " + result);
}
}

Explanation

In the example above:

  • 5 in binary is 0101
  • 3 in binary is 0011
  • Performing 0101 & 0011 results in 0001 (binary), which is 1 in decimal.

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 3+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com

No responses yet