category
Dec 9, 2025
How to Set Individual and Multiple Bits in a Java Integer - Java Code Geeks
Java Code Geeks
In Java, bit manipulation is a powerful technique that allows developers to work directly with the binary representation of numbers. Setting a specific bit means forcing a certain bit position to be 1, regardless of its previous value. This is commonly used in:
Java provides bitwise operators such as (OR), (AND), and (XOR) to perform these operations efficiently. Let us delve into understanding how to set individual and multiple Bits in a Java Integer with our comprehensive example.
To set a single bit in a number, we use the bitwise OR () operator along with a bit mask. It is represented by the Mathematical formula:
represents the original value, indicates the bit index to set using 0-based indexing, creates a mask with only the target bit set, and the (bitwise OR) operator ensures that the selected bit is forced to 1 regardless of its prior state.
To set multiple bits at once, we combine multiple bit positions into a single mask using the OR operator. It is represented by the Mathematical formula:
This creates a mask where both bit-1 and bit-3 are set to 1.
This Java program demonstrates how to set single and multiple bits in an integer using bitwise operations; the class contains two static methods where takes a number and a bit position, then uses the left shift operator to create a mask and applies the bitwise OR operator to force that specific bit to 1, while accepts an array of positions, iteratively builds a combined mask by shifting 1 to each position and merging it using OR, then applies the final mask to the original number to set multiple bits at once; in the method, the number 9 (binary ) is first used to demonstrate setting a single bit at position 1 resulting in 11 (binary ), then multiple bits at positions 2 and 3 resulting in 13 (binary ), and the results are displayed along with their binary representations using for clear visualization of how the bits change.
The output begins by displaying the original number as with its binary representat