Help with ints

Which Integer statement works best?

Q: What is the difference between using:




A: There are a few subtle differences between the code segments that you provide. Both lines give us an int. However, one is a bit more efficient than the other.

Let's consider your first statement:


Fleshing out the code a bit, we get:

Integer temp_integer = Integer.valueOf("7");
int temp_int = temp_integer.intValue();       

Breaking the code up helps us see what is going on. When you call Integer.valueOf("7"), Integer parses the "7" string and uses the parsed value to instantiate and initialize an Integer instance. Finally, intValue() retrieves the value from the Integer instance.

There is no need to flesh out the second statement, Integer.parseInt("7");. Here, Integer simply parses the "7" string and returns the int value.

The only difference between the two lines is that the first example goes out and instantiates an extra Integer instance. You would only want to actually instantiate the Integer instance if you needed to use it later; otherwise, you are needlessly instantiating an object. Object instantiation can be expensive, especially within loops. With that in mind, be sure to use valueOf() when you really need an Integer instance.

Learn more about this topic