0

With autounboxing, this statement will automatically work:

int myPrimitive = (Integer) doIt();

But if I want to explicitly convert from an Integer to an int here in a single line, where do I have to put the parentheses?

faq
  • 757
  • 2
  • 8
  • 9

2 Answers2

4

You could do this :

int myPrimitive = (int) (Integer) doIt();

But as you said, auto-unboxing will get that for you.

A bad example to show that chain casts work (don't ever use this code) :

Map notReallyAMap = (Map) (Object) new String();

The thing with chain casts, is that wherever you use it, either the cast is legit, and you can remove intermediaries; or the cast will simply cause a ClassCastException. So you should never use it.

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • A cast from an Integer to an int *IS* a case of auto-unboxing. Integer.intValue() method will do an explicit unboxing. But I do agree with one thing : **Chain cast = don't ever use this!** (+1 for that) – Eric-Karl Oct 11 '10 at 23:26
  • @Eric-Karl, It is an unboxing I agree, but not really an automatic one. – Colin Hebert Oct 12 '10 at 07:18
  • [Here is a document](http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html) about autoboxing, which tells that explicit cast/conversion is called boxing whereas autoboxing would be automatically done. – Colin Hebert Oct 12 '10 at 07:27
2

Either the compiler unboxes the Integer for you, or you do it yourself - this cannot be avoided.

So you need to either do

int myPrimitive = ((Integer) doIt()).intValue();

or more simply, change doIt() to return an int since you seem to want to deal with ints rather than (null-able) Integers.

matt b
  • 138,234
  • 66
  • 282
  • 345