Different between parseInt() and valueOf() in java?
Well, the API for Integer.valueOf(String)
does indeed say that the String
is interpreted exactly as if it were given to Integer.parseInt(String)
. However, valueOf(String)
returns a new
Integer()
object whereas parseInt(String)
returns a primitive int
.
If you want to enjoy the potential caching benefits of Integer.valueOf(int)
, you could also use this eyesore:
Integer k = Integer.valueOf(Integer.parseInt("123"))
Now, if what you want is the object and not the primitive, then using valueOf(String)
may be more attractive than making a new object out of parseInt(String)
because the former is consistently present across Integer
, Long
, Double
, etc.
From this forum:
parseInt()
returns primitive integer type (int), wherebyvalueOf
returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.
Integer.valueOf(s)
is similar to
new Integer(Integer.parseInt(s))
The difference is valueOf()
returns an Integer
, and parseInt()
returns an int
(a primitive type). Also note that valueOf()
can return a cached Integer
instance, which can cause confusing results where the result of ==
tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.
Moreover, Integer.parseInt(s)
can take primitive datatype as well.