๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Bitwise Operators in Java  


Introduction

  • Bitwise operators perform operations at the binary (bit) level on integer types such as int, long, short, byte and char.
  • Usage:
    Useful for tasks such as:
    • Low-level programming: Directly manipulating bits for hardware interaction.
    • Flags: Managing multiple boolean conditions compactly using a single integer.
    • Efficient calculations: Performing tasks like checking even/odd numbers or swapping values without additional memory.
  • Operation:
    • They operate on the binary representation of numbers, modifying individual bits based on the operator.
  • Operand Types:
    • Works only with integer data types (int, long, short, byte and char) but not with floating-point or boolean values.
  • Efficiency:
    • Bitwise operations are computationally faster than arithmetic or logical operations, making them ideal for performance-critical code.
  • Common Applications:
    • Masks: Using bit masks to extract, modify, or toggle specific bits.
    • Encryption: XOR (^) is often used in simple encryption schemes.
    • Shift Operations: Combine with shift operators (<<, >>, >>>) for tasks like scaling numbers or accessing specific bits.
  • Bitwise operators are explained as below :-
    • & (Bitwise AND Operator):
      • Purpose: Performs a bit-by-bit AND operation between two integer values. Each bit in the result is 1 if the corresponding bits in both operands are 1; otherwise, it is 0.
      • Example:
        int a = 5; // Binary: 0101  
        int b = 3; // Binary: 0011  
        System.out.println(a & b); // Output: 1 (Binary: 0001)
    • | (Bitwise OR Operator):
      • Purpose: Performs a bit-by-bit OR operation between two integer values. Each bit in the result is 1 if at least one of the corresponding bits in the operands is 1; otherwise, it is 0.
      • Example:
        int a = 5; // Binary: 0101  
        int b = 3; // Binary: 0011  
        System.out.println(a | b); // Output: 7 (Binary: 0111)
    • ^ (Bitwise XOR Operator):
      • Purpose: Performs a bit-by-bit XOR (exclusive OR) operation between two integer values. Each bit in the result is 1 if the corresponding bits in the operands are different; otherwise, it is 0.
      • Example:
        int a = 5; // Binary: 0101  
        int b = 3; // Binary: 0011  
        System.out.println(a ^ b); // Output: 6 (Binary: 0110)
    • ~ (Bitwise NOT Operator)
      • Purpose: Inverts each bit of its operand (also called one's complement). Each 1 becomes 0 and each 0 becomes 1. The result is equivalent to -(operand + 1).
      • Example:
        int a = 5; // Binary: 0101  
        System.out.println(~a); // Output: -6 (Binary: 1010 in two's complement form)
  • Program:
    public class BitwiseOperators
    {
        public static void main(String[] args)
        {
            // Initialize variables
            int a = 5;  // Binary: 0101
            int b = 3;  // Binary: 0011
    
            // Bitwise AND (&)
            System.out.println("Bitwise AND (a & b): " + (a & b)); // Output: 1 (Binary: 0001)
    
            // Bitwise OR (|)
            System.out.println("Bitwise OR (a | b): " + (a | b)); // Output: 7 (Binary: 0111)
    
            // Bitwise XOR (^)
            System.out.println("Bitwise XOR (a ^ b): " + (a ^ b)); // Output: 6 (Binary: 0110)
    
            // Bitwise Complement (~)
            System.out.println("Bitwise Complement (~a): " + (~a)); // Output: -6 (Binary: 1010 in two's complement)
    
            // Demonstrating with larger numbers
            int x = 12; // Binary: 1100
            int y = 10; // Binary: 1010
    
            System.out.println("\nWith larger numbers:");
            System.out.println("Bitwise AND (x & y): " + (x & y)); // Output: 8 (Binary: 1000)
            System.out.println("Bitwise OR (x | y): " + (x | y)); // Output: 14 (Binary: 1110)
            System.out.println("Bitwise XOR (x ^ y): " + (x ^ y)); // Output: 6 (Binary: 0110)
            System.out.println("Bitwise Complement (~x): " + (~x)); // Output: -13 (Binary: 0011 in two's complement)
        }
    }
    Output:
    Bitwise AND (a & b): 1
    Bitwise OR (a | b): 7
    Bitwise XOR (a ^ b): 6
    Bitwise Complement (~a): -6
    
    With larger numbers:
    Bitwise AND (x & y): 8
    Bitwise OR (x | y): 14
    Bitwise XOR (x ^ y): 6
    Bitwise Complement (~x): -13
Some Advance Important Points :-
  • Bitwise Operators with Literals:
    • Bitwise operators can be directly applied to literals or variables.
    • Example:
      System.out.println(5 & 3); // Output: 1
      System.out.println(8 | 2); // Output: 10
  • Supported Data Types:
    • Bitwise operators work only with integer types such as byte, short, int, long and char.
    • Applying bitwise operators to floating-point types (float, double) will result in a compilation error.
  • Bitwise NOT with Non-Integer Types:
    • The ~ operator is valid only for integer types.
    • Example: System.out.println(~5); // Output: -6
    • Using it on non-integer types like boolean or String will result in a compilation error.
  • Precedence of Bitwise Operators:
    • Bitwise operators have lower precedence than arithmetic operators but higher precedence than comparison and logical operators.
    • Example: int result = 5 + 3 & 2; // Evaluates as (5 + 3) & 2 = 8 & 2 = 0
  • Evaluation in Complex Expressions:
    • In complex expressions, bitwise operators operate on the binary representation of their operands.
    • Example: int result = (5 | 3) & 2; // Binary: (0101 | 0011) & 0010 = 0111 & 0010 = 0010 = 2
  • Impact of Data Type Size:
    • The behavior of bitwise operations is influenced by the number of bits in the data type.
    • For example, a byte uses 8 bits, so bitwise operations are limited to this range, while int uses 32 bits.
  • Sign Extension with ~:
    • The ~ operator flips all bits, including the sign bit in two's complement representation.
    • This can produce unexpected results for signed integers.
    • Example:
      int a = 5; // Binary: 00000000 00000000 00000000 00000101
      System.out.println(~a); // Binary: 11111111 11111111 11111111 11111010 = -6
  • Mixing Data Types:
    • When using bitwise operators with mixed data types, operands are promoted to int (or long if one operand is long) before the operation is performed.
    • Example:
      byte a = 5, b = 3;
      System.out.println(a & b); // Implicitly promoted to int during operation
  • Usage with Boolean Logic:
    • Bitwise operators (&, |, ^) are not interchangeable with logical operators (&&, ||).
    • Using bitwise operators with boolean values performs bitwise evaluation.
    • Example: System.out.println(true & false); // Output: false