DEV Community

Pavel Polívka
Pavel Polívka

Posted on

4 2

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

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE