0

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?

Chaitanya Karmarkar
  • 1,425
  • 2
  • 7
  • 18
  • 2
    It is fine. See: [Autoboxing and Unboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) – Jesper Apr 14 '21 at 08:44
  • Is there not any need to call any method like Integer.valueOf() for this purpose? – Chaitanya Karmarkar Apr 14 '21 at 08:45
  • 1
    No, the point of autoboxing is that this happens automatically when you assign an `int` to an `Integer`. Note: The cast in your code is unnecessary, you could just to `Integer value = intvalue;`. Read the page about autoboxing (link above), it explains it in detail. – Jesper Apr 14 '21 at 08:54

1 Answers1

1

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.

Kunu
  • 5,078
  • 6
  • 33
  • 61