Binary, Octal, and Hexadecimal Integer Literals
What you'll learn: How to write integer numbers in Java using binary, octal, and hexadecimal notation instead of the usual decimal.
Beyond Base 10
You're used to writing numbers in decimal (base 10): 42, 255, 1000. But Java lets you write integer literals in three other number systems by using special prefixes that tell the compiler which base you're using.
Think of it like speaking different "languages" for numbers—the value is the same, just expressed differently.
The Three Prefixes
Binary (Base 2) — Prefix 0b
Binary uses only 0s and 1s. Prefix your number with 0b:
int binary = 0b1010; // equals 10 in decimal
int bits = 0b11111111; // equals 255 in decimal
Octal (Base 8) — Prefix 0
Octal uses digits 0-7. Just start with a leading zero:
int octal = 077; // equals 63 in decimal
int permissions = 0755; // common in file permissions
Warning: Any number starting with 0 is octal, so 010 is NOT ten—it's eight!
Hexadecimal (Base 16) — Prefix 0x
Hex uses 0-9 and A-F. Prefix with 0x:
int hex = 0xFF; // equals 255 in decimal
int color = 0x1A2B3C; // common for colors
Why Use Different Bases?
- Binary (
0b): useful when working with individual bits or flags - Octal (
0): rare today, but appears in Unix file permissions - Hexadecimal (
0x): very common for colors, memory addresses, and compact bit representation
All four formats create regular int, long, short, or byte values—the base is just how you write them.
Key Takeaway: Use 0b for binary, 0 for octal, and 0x for hexadecimal literals; they all create the same integer types you already know.