3

Why compiler doesn't give error when we assign Integer(object) to int(primitive)?

int i;
Integer ii = new Integer(5);
i = ii;//no compilation error.

And this is the case with all other types(byte-Byte, float-Float)..

What is the reason? Am i missing something here?

5 Answers 5

13

It's called autoboxing/unboxing.

As of Java 1.5, the compiler automatically "boxes" primitives into their corresponding class (eg int and Integer, double and Double etc), and un-boxes as required.

See this page in the documentation for more details.

Sign up to request clarification or add additional context in comments.

Comments

3

Java 5 and newer are able to perform autoboxing. The compiler will implicitly transform your code into:

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

Comments

3

Java SE 5.0 introduced autoboxing as a new feature. You can find more information in the Java documentation. http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

Comments

2

i = ii;//no compilation error.

Because this is called autounboxing. When you assign object to primitive variable, value from object is taken out and assigned to primitive. this process is called autounboxing. Vice versa is Autoboxing.

Comments

2

This is called "autoboxing/unboxing". The primitive types like int are automatically converted to classes like Integer and vice-versa when it is needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.