I\'m a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API. I have the following code:
if (count.
It's better to avoid unnecessary autoboxing for 2 reasons.
For one thing, it's a bit slower than int < int
, as you're (sometimes) creating an extra object;
void doSomethingWith(Integer integerObject){ ...
int i = 1000;
doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));
The bigger issue is that hidden autoboxing can hide exceptions:
void doSomethingWith (Integer count){
if (count>0) // gets compiled into count.intValue()>0
Calling this method with null
will throw a NullPointerException
.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare()
or intValue()
, and if you've got the primitive just check the value directly.