The <code>int</code> Primitive in Java — 32-bit Integer Explained

int is Java's default integer type: a 32-bit signed two's-complement value ranging from -2 147 483 648 to 2 147 483 647. It's the type of 42, the return type of length(), and the index type for arrays.

Declaration and literals

int a = 42;              // decimal
int h = 0xFF;            // hex — 255
int o = 010;             // octal — 8  (leading zero!)
int b = 0b1010_1010;      // binary — 170 (Java 7+)
int r = 1_000_000;        // underscores for readability

Overflow — silent wrap-around

int max = Integer.MAX_VALUE;     // 2147483647
System.out.println(max + 1);     // -2147483648 — no exception
System.out.println(Math.addExact(max, 1));  // ArithmeticException ✅

If overflow matters, use Math.addExact, subtractExact, multiplyExact — they throw on overflow.

Integer division truncates

int q = 7 / 2;           // 3, not 3.5
int r = 7 % 2;           // 1 — remainder
double real = 7.0 / 2;   // 3.5 — force at least one operand to double

When int isn't enough

NeedUse
Values > 2³¹ (e.g. milliseconds since epoch)long
Arbitrary precisionBigInteger
Binary dataarray of byte
Unsigned 32-bitint with Integer.toUnsignedLong(x)

Parsing and formatting

int n = Integer.parseInt("42");              // throws NumberFormatException on bad input
int h = Integer.parseInt("FF", 16);          // 255
String hex = Integer.toString(255, 16);       // "ff"
String bin = Integer.toBinaryString(170);     // "10101010"

Common mistakes

  • Silent overflow in calculations like 1024 * 1024 * 1024 * 4. Use long or Math.multiplyExact.
  • Leading zero = octal. int x = 010; is 8, not 10.
  • Comparing Integer with == — works for −128..127 by luck. Use .equals() or intValue().

Related

Pillar: Java primitives. Siblings: long, short, byte. Also see arithmetic operators.