简体   繁体   中英

Directly casting primitive type to object is fine in Java?

I am directly casting my int primitive type variable to Integer object like below:

int intValue = 0;
Integer value = (Integer) intValue;

Is this fine or will cause some unexpected problems?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

int intValue = 0;
Integer value = intValue; // by Autoboxing

you can also convert it using valueOf method of wrapper class

Integer value = Integer.valueOf(intValue)

Check What code does the compiler generate for autoboxing? if you still have doubts.

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