Skip to main content

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​

TypeSize (Bits / Bytes)Min ValueMax ValueDefault ValueWrapper Class
byte8 bits (1 byte)-1281270Byte
short16 bits (2 bytes)-32,76832,7670Short
int32 bits (4 bytes)-2³¹2³¹ - 1 (~2.14B)0Integer
long64 bits (8 bytes)-2⁶³2⁶³ - 10LLong
float32 bits (4 bytes)IEEE-754 singleIEEE-754 single0.0fFloat
double64 bits (8 bytes)IEEE-754 doubleIEEE-754 double0.0dDouble
char16 bits (2 bytes)\u0000 (0)\uffff (65,535)\u0000Character
booleanJVM dependent (1-8b)falsetruefalseBoolean
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 ==.