Mastering Bitwise Operator in Java

Mastering Bitwise Operator in Java

6 mins read1 Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 4, 2024 17:29 IST

Have you ever wondered about the efficiency of low-level data manipulation in Java? Bitwise operators, like AND (&), OR (|), XOR (^), and shift operators (<<, >>, >>>), offer a powerful way to directly manipulate individual bits in integers, enabling fine-grained control and efficient processing in tasks such as encryption, permissions management, and more. Let's read about it!

 

Operators in Java are special symbols or keywords that are used to perform operations on variables and values. These operations can range from basic mathematical calculations to complex logical comparisons. Operators in Java are categorized into several types based on their functionality. In this blog, we will learn about one of its types in detail, which is bitwise operators!

Table of Content

 
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

โ€“ / โ€“
350 hours
Free
6 months
โ€“ / โ€“
4 months
โ€“ / โ€“
โ€“ / โ€“
โ€“ / โ€“
1 month
โ‚น50 K
7 weeks
โ‚น7.8 K
3 months
โ‚น8.47 K
2 months
โ‚น7 K
6 months
โ‚น4 K
2 months

What is a Bitwise Operator in Java?

Bitwise operators in Java are used to perform operations on individual bits of integer data types (such as byte, short, int, and long). These operators directly manipulate bits, performing binary bitwise operations. These operators are typically used in low-level programming, such as graphics, device driver programming, or algorithms where direct manipulation of bits is required. They are powerful tools for optimizing certain types of operations due to their direct action on the binary representation of data.

Types and Syntax of Bitwise Operators

Operator Type

Symbol

Syntax Example

Use Case

Notes

Bitwise AND

&

a & b

Each bit in the result is 1 if both corresponding bits in a and b are 1.

Used in masking operations.

Bitwise XOR

^

a ^ b

Each bit in the result is 1 if the corresponding bits in a and b are different.

Often used in cryptography.

Bitwise NOT

~

~a

Inverts all the bits in a.

Useful for flipping bit values.

Left Shift

<<

a << n

Shifts the bits in a to the left by n places.

Multiplication by 2n.

Right Shift

>>

a >> n

Shifts the bits in a to the right by n places, preserving the sign.

Division by 2n for non-negative numbers.

Unsigned Right Shift

>>>

a >>> n

Shifts the bits in a to the right by n places, filling with zeros.

Zero-fill right shift.

Notes

  • a and b are integer operands (can be byte, short, int, or long).
  • n in the shift operators is the number of positions to shift.
  • Bitwise AND (&) is often used in bit masking operations, where specific bits are checked.
  • Bitwise OR (|) can set specific bits in an integer.
  • XOR (^) is useful in scenarios where toggling of bits is required.
  • Bitwise NOT (~) flips every bit, which can be useful for generating bit masks.
  • Left Shift (<<) effectively multiplies the number by 2n.
  • Right Shift (>>) performs a division by 2n,  but for negative numbers, it preserves the sign.
  • Unsigned Right Shift (>>>) is used when a shift without sign preservation is needed.

Java String Compare: A Guide to Effective String Comparison in Java
Java String Compare: A Guide to Effective String Comparison in Java
Have you ever wondered how to compare strings in Java? You can use various methods for that, like using equals(), using == Operator, using equalsIgnoreCase(), using compareTo() and using compareToIgnoreCase()....read more

What are Identifiers in Java?
What are Identifiers in Java?
Have you ever wondered how Java keeps everything organized and accessible? It's all because of identifiers. Those unique labels assigned to variables, methods, and classes. These crucial elements of Java...read more

Getting Started with Java Hello World Program
Getting Started with Java Hello World Program
Do you know the significance of the "Hello World" program in Java? It's the first step for many into the world of programming, serving as a simple yet profound introduction...read more

All About Assignment Operator in Java
All About Assignment Operator in Java
Have you ever wondered how assignment operators function in Java? They are special symbols used for assigning values to variables, with the most basic one being the equal sign (=)....read more

Examples Showing Usage of Bitwise Operator

Example 1: Bitwise AND for Permission Checking

Problem Statement: In a file system, read, write, and execute permissions are represented by bits in a permission flag. Check if a user has read permission using bitwise AND.


 
public class PermissionCheck {
public static void main(String[] args) {
int permissionFlag = 5; // Binary 101, where read (4), write (2), execute (1)
int readPermission = 4; // Binary 100
// Check read permission
if ((permissionFlag & readPermission) == readPermission) {
System.out.println("Read permission granted.");
} else {
System.out.println("Read permission denied.");
}
}
}
Copy code

Output

Read permission granted.

Real-Life Scenario: This is similar to how file permissions are checked in operating systems using bitwise operations.

Example 2: Bitwise OR for Setting Flags

Problem Statement: In a graphics application, use bitwise OR to enable multiple drawing modes simultaneously (e.g., Bold and Italic).


 
public class DrawingMode {
public static void main(String[] args) {
int bold = 1; // 01 in binary
int italic = 2; // 10 in binary
int underline = 4; // 100 in binary
// Enable bold and italic
int mode = bold | italic;
System.out.println("Drawing mode: " + mode);
}
}
Copy code

Output

Drawing mode: 3

Real-Life Scenario: This approach is used in applications where multiple settings are combined into a single configuration value.

Example 3: Bitwise XOR for Simple Encryption

Problem Statement: Use bitwise XOR for a basic encryption and decryption mechanism. The same key is used for both operations.


 
public class SimpleEncryption {
public static void main(String[] args) {
char data = 'A'; // Original data
char key = 'K'; // Encryption key
// Encrypt data
char encrypted = (char)(data ^ key);
System.out.println("Encrypted data: " + encrypted);
// Decrypt data
char decrypted = (char)(encrypted ^ key);
System.out.println("Decrypted data: " + decrypted);
}
}
Copy code

Output

Encrypted data: 

Decrypted data: A

Real-Life Scenario: While simplistic, this illustrates the concept of using XOR for encryption-related tasks.

Example 4: Bitwise NOT for Inverting a Mask

Problem Statement: In image processing, use bitwise NOT to invert a color mask.


 
public class InvertMask {
public static void main(String[] args) {
int mask = 0x00FF00; // Green color mask
// Invert mask
int invertedMask = ~mask;
System.out.println("Inverted Mask: " + Integer.toHexString(invertedMask));
}
}
Copy code

Output

Inverted Mask: ffff00ff

Real-Life Scenario: In graphic design and image processing, bitwise NOT is used to manipulate color values and masks.

Example 5: Bitwise Shift for Quick Multiplication or Division

Problem Statement: In a gaming application, quickly calculate the score multiplier using bitwise shifts.


 
public class ScoreMultiplier {
public static void main(String[] args) {
int score = 50;
int multiplier = 2; // Score is to be doubled
// Double the score using left shift
int updatedScore = score << multiplier;
System.out.println("Updated Score: " + updatedScore);
}
}
Copy code

Output

Updated Score: 200

Real-Life Scenario: Bitwise shifts are often used in gaming and graphics software for quick multiplication or division by powers of two.

Array Programs in Java | Beginner to Expert Level
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more

A Guide to Power Function in Java
A Guide to Power Function in Java
Have you ever wondered how mathematical power functions are implemented in programming languages like Java? In Java, the Math.pow() function is a powerful tool used to raise a number to...read more

Java Comments | About, Types and Examples
Java Comments | About, Types and Examples
Do you know what makes the code more readable? Comments, as they provide valuable context and explanations about the code, making it easier for both the original developers and others...read more

Let's Learn Logical Operators in Java
Let's Learn Logical Operators in Java
Have you ever wondered how logical operators in Java work? These operators, including AND (&&), OR (||), and NOT (!), are used to combine or invert boolean expressions, playing a...read more

All About Arithmetic Operators in Java
All About Arithmetic Operators in Java
Have you ever wondered how arithmetic operators in Java simplify mathematical calculations? Arithmetic operators in Java are simple yet powerful tools for performing numerical computations. Let's read more about it...read more

Conclusion

Thus, while not frequently used in high-level application development, bitwise operators are indispensable tools in certain domains of programming. Understanding how to use them effectively can greatly enhance a programmer's ability to write efficient and powerful low-level code in Java.

FAQs

What are bitwise operators in Java?

Bitwise operators in Java are used to manipulate individual bits of integer values. They perform operations like AND, OR, XOR, and shift on the binary representations of numbers.

When should I use bitwise operators in Java?

Bitwise operators are often used in low-level programming, such as working with hardware or optimizing algorithms. They are useful for tasks like setting or clearing specific bits in a number, checking the parity of bits, or performing bitwise arithmetic.

What is the difference between bitwise AND and logical AND operators in Java?

Bitwise AND (&) operates on individual bits and returns a new number with bits set to 1 only where both operands have corresponding bits set to 1. Logical AND (&&) operates on boolean values and returns true if both operands are true.

Can I use bitwise operators with floating-point numbers in Java?

No, bitwise operators are designed for integer types (byte, short, int, long) and cannot be used with floating-point numbers (float, double).

How can I use bitwise operators to swap two numbers without using a temporary variable?

To swap two numbers a and b without a temporary variable, you can use XOR bitwise operator: a = a ^ b; b = a ^ b; a = a ^ b;. This technique takes advantage of the XOR property that a ^ b ^ b is equal to a.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio

Comments

(1)