Why is Integer i=5 valid statement in Java?

pavel_polivka

Pavel Polívka

Posted on September 29, 2020

Why is Integer i=5 valid statement in Java?

This question came out when I was teaching some Java basics to my friend.
In Java you have int and Integer. Integer is a wrapper class for int so logically you would need to create a new Integer like this.

Integer i = new Integer(5);

You can definitely do this, and it’s completely valid.
But you can do Integer i=5; as well.
Thanks to something called autoboxing.

Boxing is the process of wrapping a primitive value as an object of a class of the equivalent type.
Unboxing refers to the opposite direction, going from object to primitive.

So what is happening in the background. 5 is parsed like int by a compiler. Compiler notices that you want to have instance of wrapper class Integer so it autoboxes the value into the instance of Integer. This is happening in the background, no action needed.

Autoboxing lets us write nicer code. The following table shows the primitive types and their corresponding wrapper classes.

Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
💖 💪 🙅 🚩
pavel_polivka
Pavel Polívka

Posted on September 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related