Question

I have inherited code that has a rather complicated method, whose return type is Object. Depending on the inputs, this method says it is guaranteed to return different types (Integer, String, null, etc.). I am calling that method in the case where it says it is guaranteed to return an Integer. The following (obviously) does not compile:

int result;
result = foo(parameters);

The compiler complains about the type mismatch from Object to int, as well it should. However, both of the following lines compile:

result = (int) foo(parameters);
result = (Integer) foo(parameters);

I know that both calls will do what I want them to do. (For that matter, casting to short or Short would work.) My question is this: Is there any practical difference in implementation between these two casting calls, and is one better than the other with regards to best practice or performance? To clarify, I know what the difference is between primitives and wrappers, their memory usage, ability to be null and such. I'm asking only about casting from Object.

As far as I understand it, both calls will follow the same steps: 1) cast the Object to an Integer (throwing a ClassCastException if necessary), and 2) extract an int from that Integer.

I apologize if there is a duplicate question out there. I searched for it, but no question that I found answered the question of casting from Object to int.

Was it helpful?

Solution

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.

OTHER TIPS

Primitive values are efficient performance-wise that's the reason why they are made primitive. While in case of object they uses more memory but are very handy in use and provides a very useful APIs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top