0

can we change wrapper to primitive ?if not then what is happening in this code

int I = Integer.valueOf(46);
System.out.println(I);

I am not getting any error.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
garvendra
  • 11
  • 1
  • 1
    See: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html – T.J. Crowder Jul 28 '17 at 06:27
  • 1
    Surely this must have been asked and answered before. – T.J. Crowder Jul 28 '17 at 06:28
  • @T.J.Crowder: While I suspect so, at least in the context of other complexities, I'm not sure how I'd find a duplicate in amongst the thousands of other questions relating to unboxing. It's quite nice to have a question which *just* focused on this one detail, rather than it being part of the conditional expression etc. – Jon Skeet Jul 28 '17 at 06:30
  • @JonSkeet: Found one, it's quite clean. We can add others if we find them. – T.J. Crowder Jul 28 '17 at 06:30
  • @T.J.Crowder What about [How to convert Integer to int](https://stackoverflow.com/questions/3571352/how-to-convert-integer-to-int)? – Vince Jul 28 '17 at 06:31
  • @T.J.Crowder: Right. I prefer this one over that, personally - aside from anything else, in that `Long` version the unboxing is happening well before the assignment; it needs to happen for the operators to work. I'd like this version to not be *deleted*, even if it stays closed as a dupe. – Jon Skeet Jul 28 '17 at 06:32
  • @JonSkeet: A good dupe can improve the search surface, absolutely. – T.J. Crowder Jul 28 '17 at 06:35

1 Answers1

1

Yes, this is called unboxing:

Integer boxed = 10; // Boxing
int unboxed = boxed; // Unboxing

Boxing conversions are described in JLS 5.1.7; unboxing conversions are described in JLS 5.1.8.

Note that if you try to unbox a null reference, a NullPointerException will be thrown:

Integer boxed = null;
int unboxed = boxed; // NPE
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194