How is parseInt()
different from valueOf()
?
They appear to do exactly the same thing to me (also goes for parseFloat()
, parseDouble()
, parseLong()
etc, how are they different from Long.valueOf(string)
?
Also, which one of these is preferable and used more often by convention?
The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
Description. The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
Java - parseInt() Method This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With