gotchajavaCritical
Difference between parseInt() and valueOf() in Java?
Viewed 0 times
javaandbetweendifferenceparseintvalueof
Problem
How is
They appear to do exactly the same thing to me (also goes for
Also, which one of these is preferable and used more often by convention?
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?
Solution
Well, the API for
If you want to enjoy the potential caching benefits of
Now, if what you want is the object and not the primitive, then using
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.Code Snippets
Integer k = Integer.valueOf(Integer.parseInt("123"))Context
Stack Overflow Q#508665, score: 487
Revisions (0)
No revisions yet.