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?
15
I need to convert a String
in int
, and I came across these two options, which have an equal result.
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.
Browser other questions tagged java string int
You are not signed in. Login or sign up in order to post.
Just to clarify what was not evident in the answer:
Integer.parseInt()
returns aint
(primitive type) whereasInteger.valueOf()
returns aInteger
(object wrapper immutable that "surrounds" the primitive type). The choice will depend on the type of data you need (probably in most cases will beInteger.parseInt()
), remembering that in repetitive operations the Boxing/Unboxing (conversion ofint
forInteger
and vice versa) can consume a certain processing.– Piovezan
That’s right, I wouldn’t have tried that.
– Gustavo Cinque