Integer Literals: Decimal, Hexadecimal, Octal, and Binary
What you'll learn: How to write integer numbers in different number systems using special prefix notations in Java.
The Core Idea
When you write a number like 42 in Java, you're using the decimal (base-10) system—the way we normally count. But sometimes, especially when working with low-level data or memory addresses, other number systems are more convenient. Java lets you write integer literals in four different formats:
- Decimal (base-10): No prefix —
42 - Hexadecimal (base-16): Prefix
0xor0X—0x2A - Octal (base-8): Prefix
0—052 - Binary (base-2): Prefix
0bor0B—0b101010
All four of these represent the same value—just written in different number systems.
Think of It Like Languages
It's like saying "hello" in different languages—English, Spanish, French—all mean the same greeting. Similarly, 42, 0x2A, 052, and 0b101010 all mean the same number, just expressed in different "languages" of counting.
Example in Code
int decimal = 42;
int hex = 0x2A; // 2×16 + 10 = 42
int octal = 052; // 5×8 + 2 = 42
int binary = 0b101010; // 32+8+2 = 42
System.out.println(decimal); // prints: 42
System.out.println(hex); // prints: 42
System.out.println(octal); // prints: 42
System.out.println(binary); // prints: 42
All four variables hold the exact same value. Java converts them all to the same internal representation.
Key Takeaway: Java supports four integer literal formats—decimal (no prefix), hexadecimal (0x), octal (0), and binary (0b)—all representing the same underlying values in different number systems.