Command Palette

Search for a command to run...

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

Permission flags in one int

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?

Permission flags in one int
Sign in to run this example in your browser.

Expected output

perms          = 11
can write?       true
can execute?     false
grant execute  = 111
revoke write   = 101
toggle read    = 100