Browse Tutorials
What is a Bitwise Operator in Java? Type, Example and More

What is a Bitwise Operator in Java? Type, Example and More

26 Feb 2024
Beginner
318 Views
13 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Bitwise Operators in Java: An Overview

Bitwise operators in Java are powerful tools that allow you to manipulate individual bits of data within primitive data types. Java tutorial will help you a lot if you're interested in mastering the bitwise operators in Java. Previously we learned about different types of operators briefly. In this article on bitwise operators, we will take an in-depth look at what bitwise operators are, their syntax, and types; when they should be used, and some practical implementations.

What is a Bitwise Operator in Java?

Bitwise operators in Java allow you to control individual bits of data within integer types. These operators provide binary-level operations, allowing developers to work with the underlying binary data representation. Understanding bitwise operators is essential for low-level data manipulation activities like cryptography, image processing, and network programming.

Explore More Operators:

  1. Assignment operator in Java
  2. Unary operator in Java
  3. Arithmetic operators in Java
  4. Relational operators in Java
  5. Logical operators in Java
  6. Ternary Operator in Java

Syntax:

Here is the Java syntax for relational operators:
operand1 binary_operator operand2

Types of Bitwise Operators in Java

Types of Bitwise Operators in Java

The truth table of a bitwise operator in C:

XYX&YX/YX^Y
00000
01011
10011
11111

1. AND Operator (&)

The bitwise AND operator (&) compares each bit of two operands. If both bits are 1, the corresponding result bit is set to 1; otherwise, it is set to 0.

Example:

import java.util.Scanner;

public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5;  // binary: 0101
     int b = 3;  // binary: 0011
    int result = a & b;  // binary: 0001
    System.out.println(result);  // Output: 1
}
}

The AND operator is commonly used for masking and clearing specific bits in a value.

Output

1

2. OR Operator (|)

The bitwise OR operator (|) compares each bit of two operands. If at least one of the bits is 1, the corresponding result bit is set to 1.

Example:

import java.util.Scanner;

public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5; // binary: 0101
      int b = 3;  // binary: 0011
      int result = a | b; // binary: 0111
      System.out.println(result);
}
}

The OR operator is often used for setting specific bits in a value.

Output

7

3. XOR Operator (^)

The bitwise XOR operator (^) compares each bit of two operands. If the bits are different, the corresponding result bit is set to 1; otherwise, it is set to 0.

Example:

import java.util.Scanner;

public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5;  // binary: 0101
      int b = 3;  // binary: 0011
      int result = a ^ b;  // binary: 0110
      System.out.println(result);  // Output: 6
}
}

The XOR operator is useful for flipping bits or checking for differences between two values.

Output

6

4. NOT Operator (~)

The bitwise NOT operator (~) inverts each bit of the operand. It changes 1s to 0s and 0s to 1s.

Example:

import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5;  // binary: 0101
      int result = ~a;  // binary: 1010 (inverted)
     System.out.println(result);  // Output: -6 (in decimal)
}
}

The NOT operator is often used for creating the two's complement of a binary number, and it can also be used for bitwise negation.

Output

-6

5. Left Shift Operator (<<)

The left shift operator (<<) shifts the bits of the left operand to the left by a specified number of positions. The vacant positions on the right are filled with zeros.

Example:

import java.util.Scanner;

public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5;  // binary: 0101
      int result = a << 2;  // binary: 10100
      System.out.println(result);  // Output: 20
}
}

Left shifting is equivalent to multiplying the value by 2 raised to the power of the shift count.

Output

20

6. Right Shift Operator (>>)

The right shift operator (>>) shifts the bits of the left operand to the right by a specified number of positions. The vacant positions on the left are filled based on the sign bit (arithmetic right shift for signed integers).

Example:

import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
	int a = 20;  // binary: 10100
      int result = a >> 2;  // binary: 00101
      System.out.println(result);  // Output: 5
}
}    

Right shifting is equivalent to dividing the value by 2 raised to the power of the shift count.

Output

5

Practical Use Cases

1. Setting and Clearing Bits:

  • Bitwise operators are commonly used for setting and clearing specific bits within a binary representation, especially when working with hardware registers or flags.

2. Optimizing Algorithms:

  • Bitwise operations can be used to optimize certain algorithms, such as those related to graphics processing, compression, and encryption.

3. Bit Manipulation for Compact Storage:

  • In scenarios where memory is a critical resource, bitwise operations can be employed to store multiple Boolean values in a single integer.

4. Network Programming:

  • Bitwise operations are valuable in network programming for tasks like creating custom protocols and manipulating IP addresses.

Bitwise Operators in Java vs. Logical Operators in Java

While bitwise operators work with single bits, logical operators (&&, ||, !) work with Boolean expressions. Bitwise operators are better suitable for low-level bit manipulation, whereas logical operators are better suited for Boolean condition evaluation.
Bitwise OperatorsLogical Operators
The programming language offers the bitwise operator kind of operator to carry out calculations.An operator type offered by the programming language to carry out logic-based operations is known as a logical operator.
Bit-by-bit operations are carried out by bitwise operators, who operate on bits.A decision is made based on several conditions using logical operators.
Integer operands are used by bitwise operators. Expressions that produce a Boolean value are subject to the operations of logical operators.
These are utilized for bit manipulation tasks like bit checking, bit setting, and bit clearing.These are used to determine whether the expression complies with certain requirements.
Bitwise operations produce an integer value as their output.A Boolean value, which can either be true or false, is the outcome of logical operators.

Summary

After understanding the principles of bitwise operators in Java, it's time to master this complex concept. You'll get proficient with practice. Keep in mind that there is a connection between maths and computing below grammatical difficulties. Bitwise operators improve your coding abilities and set you apart from competing methods. Explore the bitwise operator in Java online Training to expand your knowledge of programming.

FAQs

Q1. What is Bitwise and logical AND in Java?

  • Bitwise AND (&): In C, bitwise AND is an operator that performs a bitwise AND operation on each pair of corresponding bits in two operands. The result is a new value where each bit is the result of the AND operation between the corresponding bits of the operands.
  • Logical AND (&&): Logical AND, on the other hand, is a boolean operator that evaluates two boolean expressions and returns true if both expressions are true. It short-circuits the evaluation, meaning that if the first expression is false, the second expression is not evaluated.

Q2. What is the difference between Bitwise and logical operators?

  • Bitwise Operators: Operate at the binary level, manipulating individual bits within data. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
  • Logical Operators: Work on boolean expressions, evaluating conditions, and returning true or false. They include AND (&&), OR (||), and NOT (!). Logical operators short-circuit, meaning they may not evaluate the second operand if the result can be determined from the first operand.

Q3. What is the & symbol in bitwise?

In bitwise operations, the & symbol represents the AND operator. It performs a bitwise AND operation on each pair of corresponding bits in two operands. The result is a new value where each bit is the result of the AND operation between the corresponding bits of the operands.

Q4. What is the difference between OR and XOR?

  • OR (|) Operator: Performs a bitwise OR operation on each pair of corresponding bits in two operands. The result is 1 if at least one of the bits is 1.
  • XOR (^) Operator: Performs a bitwise exclusive OR operation on each pair of corresponding bits in two operands. The result is 1 if the bits are different; otherwise, the result is 0.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this