In this Blog we will find answer for following questions

  • What is Primitive Type.
  • What is Wrapper Class.
  • Convert one into another.
  • Ideal scenario to use Primitive vs Wrapper.

Primitive Type

Primitive types directly contain values. Java defines many primitive type variables. We will see mainly int vs Integer.

int is a Primitive Type. Variables of type int store the actual binary value for the integer. int variables are mutable.

Wrapper class

A class whose object wraps or contains a primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data types.

Integer is a class with a single field of type int. Variables of type Integer store references to Integer objects. Integers are immutable.

Following code is definition of Integer.class to give you an overview

public final class Integer extends Number implements Comparable<Integer> {

@Native public static final int MIN_VALUE = 0x80000000;

@Native public static final int MAX_VALUE = 0x7fffffff;


Interchange them

// Convert Integer to int (aa to a)
int a = aa.intValue();

// Convert int to Integer (x to xx)
Integer xx = new Integer( x );

Note on Auto boxing

Since java 5 we have auto boxing, and the conversion between primitive and wrapper class is done automatically. So Integer n = 9;  is same as Integer n = new Integer(9).

Which one to use when???

Use int in following case:

  • Since primitive contain value its ideal candidate for performing operations.
  • Not null values

Use Integer in following case:

  • Methods that take objects (including generic types like List<T>) will implicitly require the use of Integer.
  • Use of Integer is relatively cheap for low values (-128 to 127) because of interning as default range of cache is -128 to 127. Use Integer.valueOf(int) instead of new Integer(int). 
  • null values
  • Since Primitive wrapper classes are immutable they can be used in multi threading environment.

Note: Everything I discuss here applies analogously to

  • byte vs Byte
  • short vs Short
  • long vs Long
  • boolean vs Boolean
  • char vs Character
  • float vs Float
  • double vs Double


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *