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

Asked

Viewed 10,089 times

15

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

  • Is there any difference between them?
  • Is there any rule/convention that says which to use or is indifferent?

1 answer

14


There’s not much difference.

In fact the Integer.valueOf(String) returns a new Integer(Integer.parseInt(String)). then he uses Integer.parseInt(String) within himself.

Observing the codes, the method parseInt() has a whole String manipulation for errors, and incongruous variables, while the method valueOf() does is return Integer.valueOf(parseInt(s, 10));.

Within the super method valueOf() is checked if the value passed is greater than -128, and less than 127, if yes, the method searches in an array, called cache and located in the class IntegerCache, its position and the corresponding value, which would be the same, if it does not take into account the if is given a return of a new Integer(Integer).

If one is better than the other, I wouldn’t know. I believe that in the matter of processing the valueOf() would be better used, while in the matter of speed of execution the parseInt() would be faster. I would prefer to choose the valueOf() as standard, for reasons of optimization.

Source: Integer

EDITION:

After a while, I think it’s best to attach this information with the official answer. As said by @Piovezan:

Integer.parseint() returns an int (primitive type) while 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.

  • 4

    Just to clarify what was not evident in the answer: Integer.parseInt() returns a int (primitive type) whereas Integer.valueOf() returns a Integer (object wrapper immutable that "surrounds" the primitive type). The choice will depend on the type of data you need (probably in most cases will be Integer.parseInt()), remembering that in repetitive operations the Boxing/Unboxing (conversion of int for Integer and vice versa) can consume a certain processing.

  • That’s right, I wouldn’t have tried that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.