简体   繁体   中英

Why Compiler doesn't give error when we assign Integer to int in Java

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?

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.

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

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();

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM