: They are discarded
In Core Java, when you perform bitwise shifting operations (left shift <<
or right shift >>
), the bits that “fall off” or go beyond the boundaries of the variable are discarded. For left shift (<<
), zeros are filled in from the right, and for right shift (>>
), the sign bit (the leftmost bit, which indicates the sign of the number in signed data types like int
) is used to fill in from the left.
Here’s a brief explanation:
- Left Shift (
<<
):- Bits are shifted to the left.
- The vacated bits on the right are filled with zeros.
- Example:
java
int num = 5; // binary: 0000 0101
int result = num << 2; // binary: 0001 0100 (left shift by 2)
- Right Shift (
>>
):- Bits are shifted to the right.
- For positive numbers, the vacated bits on the left are filled with zeros.
- For negative numbers, the vacated bits on the left are filled with the sign bit (1 for negative numbers, 0 for positive numbers).
- Example:
java
int num = -8; // binary: 1111 1000 (two's complement for -8)
int result = num >> 2; // binary: 1111 1110 (right shift by 2, sign bit is used to fill)
In both cases, the bits that “fall off” during the shift operation are discarded. It’s important to be aware of these behaviors, especially when working with bitwise operations in Java.