Difference between parseInt and valueOf in java?

What's the difference between these two methods? 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) ?

Edit: Also, which of these is preferable and used more often by convention?


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), 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.


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.

链接地址: http://www.djcxy.com/p/3552.html

上一篇: 将String转换为Java中的double

下一篇: java中parseInt和valueOf之间的区别?