Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different between parseInt() and valueOf() in java?

Tags:

java

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?

like image 211
Ali Avatar asked Feb 03 '09 19:02

Ali


People also ask

What is use of valueOf () in java?

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.

What is parseInt () in java?

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 .

When parseInt () method can be used?

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.


2 Answers

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.

like image 56
Zach Scrivena Avatar answered Sep 30 '22 19:09

Zach Scrivena


From this forum:

parseInt() returns primitive integer type (int), whereby valueOf 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.

like image 20
Michael Haren Avatar answered Sep 30 '22 19:09

Michael Haren