The Wayback Machine - https://web.archive.org/web/20241126231942/https://www.geeksforgeeks.org/bitwise-operators-in-java/
Open In App

Bitwise Operators in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: 

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

This article explains all that one needs to know regarding Bitwise Operators. 

Bitwise Operators

Bitwise operators are used to performing the manipulation of individual bits of a number which can be useful for optimizing performance in certain cases. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees. For a more detailed understanding of bitwise operations, the Java Programming Course offers examples and coding challenges to help you master this topic

Now let’s look at each one of the bitwise operators in Java: 

1. Bitwise OR (|) 

This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0. 

Example:

a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7
  0101
| 0111
 ________
  0111  = 7 (In decimal) 

2. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0. 

Example:

a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7
  0101
& 0111
 ________
  0101  = 5 (In decimal) 

3. Bitwise XOR (^) 

This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0. 

Example:

a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7
  0101
^ 0111
 ________
  0010  = 2 (In decimal) 

4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0. 

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5 in java (8 bits)

~ 00000101
 ________
  11111010  = 246 (In decimal) 

Twist in Bitwise Complement Operator in Java

The bitwise complement of 5 is 246 and The 2’s complement of 246 is -6. Hence, the output is -6 instead of 246.

bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N = -(~(~N)+1)  =  -(N+1). 

For Example: The 2’s complement of a number is equal to the complement of that number + 1 .

Bitwise complement

2’s Complement


Illustration:

Java
// Java program to illustrate
// bitwise operators

public class operators {
    public static void main(String[] args)
    {
        // Initial values
        int a = 5;
        int b = 7;

        // bitwise and
        // 0101 & 0111=0101 = 5
        System.out.println("a&b = " + (a & b));

        // bitwise or
        // 0101 | 0111=0111 = 7
        System.out.println("a|b = " + (a | b));

        // bitwise xor
        // 0101 ^ 0111=0010 = 2
        System.out.println("a^b = " + (a ^ b));

        // bitwise not
        // ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010
        // will give 2's complement (32 bit) of 5 = -6
        System.out.println("~a = " + ~a);

        // can also be combined with
        // assignment operator to provide shorthand
        // assignment
        // a=a&b
        a &= b;
        System.out.println("a= " + a);
    }
}

Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
  • Auxiliary space:O(1) 
  • Time complexity:O(1) 
Java
// Demonstrating the bitwise logical operators


class GFG {
    public static void main (String[] args) {
      
        String binary[]={
          "0000","0001","0010","0011","0100","0101",
          "0110","0111","1000","1001","1010",
          "1011","1100","1101","1110","1111"
        };
      
      // initializing the values of a and b 
      int a=3; // 0+2+1 or 0011 in binary
      int b=6; // 4+2+0 or 0110 in binary
      
      // bitwise or
      int c= a | b;
      
      // bitwise and
      int d= a & b;
      
      // bitwise xor
      int e= a ^ b;
      
      // bitwise not
      int f= (~a & b)|(a &~b);
      int g= ~a & 0x0f;
      
      
      System.out.println(" a= "+binary[a]);
      System.out.println(" b= "+binary[b]);
      System.out.println(" a|b= "+binary[c]);
      System.out.println(" a&b= "+binary[d]);
      System.out.println(" a^b= "+binary[e]);
      System.out.println("~a & b|a&~b= "+binary[f]);
      System.out.println("~a= "+binary[g]);
    }
}

Output
 a= 0011
 b= 0110
 a|b= 0111
 a&b= 0010
 a^b= 0101
~a & b|a&~b= 0101
~a= 1100

Bit-Shift Operators (Shift Operators) 

Shift operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. 

Syntax: 

 number shift_op number_of_places_to_shift;

Types of Shift Operators:

Shift Operators are further divided into 3 types. These are:

  1. Signed Right shift operator (>>)
  2. Unsigned Right shift operator (>>>)
  3. Left shift operator(<<)

Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java.

Program to implement all Bitwise operators in Java for user input

Java
import java.util.Scanner;

public class BitwiseOperators {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int num1 = input.nextInt();

        System.out.print("Enter second number: ");
        int num2 = input.nextInt();

        System.out.println("Bitwise AND: " + (num1 & num2));
        System.out.println("Bitwise OR: " + (num1 | num2));
        System.out.println("Bitwise XOR: " + (num1 ^ num2));
        System.out.println("Bitwise NOT: " + (~num1));
        System.out.println("Bitwise Left Shift: " + (num1 << 2));
        System.out.println("Bitwise Right Shift: " + (num1 >> 2));
        System.out.println("Bitwise Unsigned Right Shift: " + (num1 >>> 2));

        input.close();
    }
}

Input

Enter first number: 4
Enter second number: 8

Output

Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1

Explanation:

This program prompts the user to enter two numbers, num1 and num2. It then performs the following bitwise operations using the &, |, ^, ~, <<, >>, and >>> operators:

  • Bitwise AND
  • Bitwise OR
  • Bitwise XOR
  • Bitwise NOT
  • Bitwise Left Shift
  • Bitwise Right Shift
  • Bitwise Zero Fill Right Shift

Advantages: 

The advantages of using Bitwise Operators in Java are:

  • Speed: Bitwise operations are much faster than arithmetic operations as they operate directly on binary representations of numbers.
  • Space Optimization: Bitwise operations can be used to store multiple values in a single variable, which can be useful when working with limited memory.
  • Bit Manipulation: Bitwise operators allow for precise control over individual bits of a number, which can be useful in various applications such as cryptography, error detection, and compression.
  • Code Simplification: Bitwise operations can simplify the code by reducing the number of conditional statements and loops required to perform certain tasks.

In summary, Bitwise Operators are an important tool for optimizing performance, improving code readability, and reducing code complexity in Java applications.



Previous Article
Next Article

Similar Reads

Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator '>>' which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here w
2 min read
Complete Reference for Bitwise Operators in Programming/Coding
There exists no programming language that doesn't use Bit Manipulations. Bit manipulation is all about these bitwise operations. They improve the efficiency of programs by being primitive, fast actions. There are different bitwise operations used in bit manipulation. These Bitwise Operators operate on the individual bits of the bit patterns. Bit op
13 min read
Java | Operators | Question 1
Predict the output of following Java Program class Test { public static void main(String args[]) { int x = -4; System.out.println(x>>1); int y = 4; System.out.println(y>>1); } } (A) Compiler Error: Operator >> cannot be applied to negative numbers (B) -2 2 (C) 2 2 (D) 0 2 Answer: (B) Explanation: See https://www.geeksforgeeks.org/
1 min read
Java | Operators | Question 2
Predict the output of following Java program. Assume that int is stored using 32 bits. class Test { public static void main(String args[]) { int x = -1; System.out.println(x>>>29); System.out.println(x>>>30); System.out.println(x>>>31); } } (A) 7 3 1 (B) 15 7 3 (C) 0 0 0 (D) 1 1 1 Answer: (A) Explanation: Please see https
1 min read
Java | Operators | Question 3
class Test { public static void main(String args[]) { System.out.println(10 + 20 + "GeeksQuiz"); System.out.println("GeeksQuiz" + 10 + 20); } } (A) 30GeeksQuiz GeeksQuiz30 (B) 1020GeeksQuiz GeeksQuiz1020 (C) 30GeeksQuiz GeeksQuiz1020 (D) 1020GeeksQuiz GeeksQuiz30 Answer: (C) Explanation: In the given expressions 10 + 20 + "Geeks
1 min read
Java | Operators | Question 4
class Test { public static void main(String args[]) { System.out.println(10*20 + "GeeksQuiz"); System.out.println("GeeksQuiz" + 10*20); } } (A) 10*20GeeksQuiz GeeksQuiz10*20 (B) 200GeeksQuiz GeeksQuiz200 (C) 200GeeksQuiz GeeksQuiz10*20 (D) 1020GeeksQuiz GeeksQuiz220 Answer: (B) Explanation: Precedence of * is more than +.Quiz of
1 min read
Java | Operators | Question 5
Which of the following is not an operator in Java? (A) instanceof (B) sizeof (C) new (D) >>>= Answer: (B) Explanation: There is no sizeof operator in Java. We generally don't need size of objects.Quiz of this Question
1 min read
Java | Operators | Question 6
class Base {} class Derived extends Base { public static void main(String args[]){ Base a = new Derived(); System.out.println(a instanceof Derived); } } (A) true (B) false Answer: (A) Explanation: The instanceof operator works even when the reference is of base class type.Quiz of this Question
1 min read
Java | Operators | Question 7
class Test { public static void main(String args[]) { String s1 = "geeksquiz"; String s2 = "geeksquiz"; System.out.println("s1 == s2 is:" + s1 == s2); } } (A) true (B) false (C) compiler error (D) throws an exception Answer: (B) Explanation: The output is “false” because in java + operator precedence is more than == op
1 min read
Java | Operators | Question 8
class demo { int a, b, c; demo(int a, int b, int c) { this.a = a; this.b = b; } demo() { a = b = c = 0; } demo operator+(const demo &obj) { demo object; object.a = this.a + obj.a; object.b = this.b + obj.b; object.c = this.c + obj.c; return object; } } class Test { public static void main(String[] args) { demo obj1 = new demo(1, 2, 3); demo obj
1 min read
Java | Operators | Question 9
Predict the output of the following program. Java Code class Test { boolean[] array = new boolean[3]; int count = 0; void set(boolean[] arr, int x) { arr[x] = true; count++; } void func() { if(array[0] && array[++count - 2] | array [count - 1]) count++; System.out.println("count = " + count); } public static void main(String[] args) { Test object =
1 min read
Java Arithmetic Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
10 min read
Short Circuit Logical Operators in Java with Examples
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to effi
3 min read
Java Assignment Operators with Examples
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
7 min read
Basic Operators in Java
Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic/mathemat
10 min read
Compound assignment operators in Java
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a
7 min read
Java Logical Operators with Examples
Logical operators are used to perform logical "AND", "OR" and "NOT" operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND
10 min read
Interesting facts about Increment and Decrement operators in Java
Increment operator is used to increment a value by 1. There are two varieties of increment operator:  Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first and then the result is computed.Example [GFGTABS] Java //INCREMENTAL OPERATOR //Let's see what exactly happens when we u
5 min read
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types. What are the Java Operators?Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks
15 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Maximum and minimum sum of Bitwise XOR of pairs from an array
Given an array arr[] of size N, the task is to find the maximum and minimum sum of Bitwise XOR of all pairs from an array by splitting the array into N / 2 pairs. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6 10Explanation:Bitwise XOR of the all possible pair splits are as follows:(1, 2), (3, 4) → 3 + 7 =10.(1, 3), (2, 4) → 2 + 6 = 8.(1, 4), (2, 3
11 min read
Bitwise Complement Operator (~ tilde)
Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde). Example: Input
3 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
three90RightbarBannerImg