Command Palette

Search for a command to run...

Back to the lesson: Topic 1.9 — Bitwise and Shift Operators
Core Java · Example 2 of 4

Shifts with negative numbers and big distances

Bitwise operators (&, |, ^, ~) work on the individual bits of integers, and shift operators (<<, >>, >>>) slide those bits left or right. They're how Java packs many flags into one number, tests for odd numbers and powers of two in one step, and how HashMap picks a bucket.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the number of 1-bits in 255, in 256 and in -1, using Integer.bitCount.

02

Store four on/off settings (bold, italic, underline, strike) in one int, turn on bold and underline, then print which are on.

03

Without using % or /, print whether 37 and 48 are even, and print 48 divided by 8 using a shift.

Explain it without notes

01

Explain the difference between >> and >>> with a negative number.

02

Why is n > 0 && (n & (n - 1)) == 0 a test for powers of two?

03

How do you set, clear, toggle and test one flag bit in an int?

04

Why does 1 << 32 evaluate to 1 in Java?

Shifts with negative numbers and big distances
Sign in to run this example in your browser.

Expected output

n          = 11111111111111111111111111110000
n >> 2     = -4
n >>> 2    = 1073741820
n >>> 28   = 15
-7 >> 1    = -4   but -7 / 2 = -3
1 << 31    = -2147483648
1 << 32    = 1
1L << 32   = 4294967296
raw        = -16
raw & 0xFF = 240