In practical terms, there is not a huge difference in performance between using int
and Integer
. One is technically faster as a primitive, and one has useful class-related methods you can use.
As far as "casting", if foo()
returns an Integer
in its method code, there will be 0 performance loss when casting to an Integer
, since the Object
returned is already an Integer
.
If foo()
returns an int
there will be a slight cost to cast it to a primitive, but nothing noticeable.
public Object fooInt() {
return 5;
}
public Object fooInteger() {
return new Integer(5);
}
Integer integerResult = (Integer)fooInteger(); //No cost
integerResult = (Integer)fooInt(); //Small casting cost
int intResult = (int)fooInteger(); //Small casting cost
intResult = (int)fooInt(); //No cost
Instead, look at whether or not it would be more useful to use an int
versus an Integer
with what you do with the result object later down the line. The cost to cast an int
to an Integer
is completely negligible in Java.