Difference between Integer.valueOf (String) and Integer.parseInt (String)


I need to convert a String to int , and I came across these two options, which have an equal result.

  • Is there any difference between them?
  • Is there a rule / convention that says which to use or is indifferent?
asked by anonymous 09.12.2014 / 12:09

1 answer


There's not much difference.

Actually Integer.valueOf(String) returns new Integer(Integer.parseInt(String)) . so it uses Integer.parseInt(String) within itself.

Looking at the codes, the parseInt() method has all the String manipulation for errors, and incongruent variables, whereas what the valueOf() method does is return Integer.valueOf(parseInt(s, 10)); .

In the super method%% is checked if the passed value is greater than -128, and less than 127, if yes, the method looks in an array, called valueOf() and located in class cache its position and with the corresponding value, which would be the same, if it does not meet the IntegerCache is given a return of a if .

If one is better than the other, I could not say. I believe that in terms of processing the new Integer(Integer) would be better used, while in the matter of speed of execution the valueOf() would be faster. I would prefer to choose parseInt() as default, for optimization reasons.

Source: Integer


After a while, I think it's better to attach this information to the official response. As said by @Piovezan:


Integer.parseInt () returns an int (primitive type) whereas Integer.valueOf () returns an Integer (immutable wrapper object that "wraps" the primitive type). The choice will depend on the type of data you need (probably in most cases it will be Integer.parseInt ()), remembering that in repetitive operations boxing / unboxing (conversion from int to Integer and vice versa) can consume a certain processing.

09.12.2014 / 12:26