Java int vs Integer

Java has the concept of both int and Integer when it comes to storing integer type data. The main difference between the two is that int is primitive, where Integer is wrapper class. Creating an Integer is basically creating an object with a single int variable inside.

Every primitive type in Java has an equivalent wrapper class:

  • byte has Byte
  • short has Short
  • int has Integer
  • long has Long
  • boolean has Boolean
  • char has Character
  • float has Float
  • double has Double

Therefore the below should apply to all of the above.

int is more basic, and because of this it is much smaller and therefore can be faster to use. int‘s are mutable, which means they can be changed and updated, unless you mark them as final.

Integers are bigger as they are an object containing an int, basically a box with an int inside.

They are also immutable, and cannot be changed without creating a new Integer object.

Which to Use

Both have their uses, here is a useful table of the pros and cons of each:

Source: https://www.mindprod.com/jgloss/intvsinteger.html

You can convert between the two:

int i = ii.intValue();
Integer ii = new Integer(i);

This process is called Boxing/Unboxing. If you think about the example I said earlier of Integer being int in a box, it makes sense.

Boxing is converting a primitive (int) to an Object (Integer), placing it in the box.
Unboxing is converting an Object (Integer) to a primitive (int), taking it out of the box.

In Java 1.5, Autoboxing was introduced which does the conversion for you automatically when the code is compiled.

This comes in handy when you are using Collections for example.

ArrayList<int> al = new ArrayList<int>(); // not supported 

ArrayList<Integer> al = new ArrayList<Integer>(); // supported 

al.add(45); //Autoboxing

We cannot create the ArrayList using the primitive int, so we must use Integer. However we can add int‘s into the array, as the Java compiler will Autobox it.

While useful, Autoboxing can lead to issues.

  • If there are lots of conversions happening when compiling, there will be a penalty to performance.
  • Could cause an Out of Memory exception if the autoboxing increases the size of the program too much.
  • May cause null pointers trying to convert from an Object that allows nulls to a primitive that doesn’t.

There are some other issues you can read about here.


You can find the list of all of my Knowledge Sharing posts here.

One thought on “Java int vs Integer

Leave a comment