Javabeginner5 min read

Java int vs Integer: Difference Between Primitive and Wrapper Types

Understanding the difference between primitive int and wrapper Integer class in Java, including memory usage, nullability, and performance implications.

#java#primitives#wrapper-classes#data-types

In Java, int is a primitive data type that stores raw integer values directly in memory, while Integer is a wrapper class that wraps an int value into an object. This fundamental difference affects memory usage, nullability, and performance in your applications.

Key Differences

  • Memory: int uses 4 bytes of memory; Integer uses additional memory for object overhead
  • Nullability: int cannot be null; Integer can be null
  • Performance: int is faster for arithmetic operations

Code Example

java
// Primitive type
int primitiveNum = 100;

// Wrapper Class object
Integer wrapperNum = Integer.valueOf(100);

System.out.println("Primitive: " + primitiveNum);
System.out.println("Wrapper: " + wrapperNum);

Output

Primitive: 100
Wrapper: 100
💡

Remember This

  • Primitive data types use lowercase (int), wrapper classes use capital letters (Integer)
  • int is stored on stack, Integer is stored on heap
  • Integer provides utility methods like parseInt(), toString()
📌

Important Rules

  • String starts with a capital S because it is a class, not a primitive
  • Always use Integer when you need nullability (e.g., database fields)
  • Use int for high-performance arithmetic operations
⚠️

Common Mistakes

  • Comparing Integer objects with == instead of .equals() for values outside -128 to 127
  • Forgetting to handle NullPointerException when unboxing null Integer
  • Using Integer in tight loops where performance is critical
Java int vs Integer: Primitive vs Wrapper Types Explained | Afzaal Suleman