2.3 Data Types, Primitives & Wrapper Classes
← Back to Chapter 2: Java Overview & Memory Model
Java is a statically typed language. Every variable must have a declared type before compilation. Java's type system divides into 8 Primitive Types and Reference Types.
1. The 8 Primitive Types in Java
| Type | Size (Bits / Bytes) | Min Value | Max Value | Default Value | Wrapper Class |
|---|---|---|---|---|---|
byte | 8 bits (1 byte) | -128 | 127 | 0 | Byte |
short | 16 bits (2 bytes) | -32,768 | 32,767 | 0 | Short |
int | 32 bits (4 bytes) | -2³¹ | 2³¹ - 1 (~2.14B) | 0 | Integer |
long | 64 bits (8 bytes) | -2⁶³ | 2⁶³ - 1 | 0L | Long |
float | 32 bits (4 bytes) | IEEE-754 single | IEEE-754 single | 0.0f | Float |
double | 64 bits (8 bytes) | IEEE-754 double | IEEE-754 double | 0.0d | Double |
char | 16 bits (2 bytes) | \u0000 (0) | \uffff (65,535) | \u0000 | Character |
boolean | JVM dependent (1-8b) | false | true | false | Boolean |
Financial Calculations: Avoid float/double
Never use float or double for currency or exact financial balances due to floating-point rounding inaccuracies. Always use java.math.BigDecimal.
2. Autoboxing & The Integer Cache Trap
Java compiler automatically converts between primitives and their wrapper classes:
Integer a = 100; // Autoboxing: Integer.valueOf(100)
int b = a; // Unboxing: a.intValue()
The Integer Cache Gotcha (-128 to 127)
Java caches Integer objects between -128 and 127 (per JLS §5.1.7):
Integer x = 127;
Integer y = 127;
System.out.println(x == y); // true (Both refer to same cached instance)
Integer p = 128;
Integer q = 128;
System.out.println(p == q); // false (Two separate Heap objects!)
System.out.println(p.equals(q)); // true (Compares underlying int value)
Best Practice
Always compare object wrappers using .equals(), never ==.