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?
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.
Look at Java sources: valueOf
is using parseInt
:
/**
* Parses the specified string as a signed decimal integer value.
*
* @param string
* the string representation of an integer value.
* @return an {@code Integer} instance containing the integer value
* represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
* @see #parseInt(String)
*/
public static Integer valueOf(String string) throws NumberFormatException {
return valueOf(parseInt(string));
}
parseInt
returns int
(not Integer
)
/**
* Parses the specified string as a signed decimal integer value. The ASCII
* character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
*/
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
}
Integer.parseInt can just return int as native type.
Integer.valueOf may actually need to allocate an Integer object, unless that integer happens to be one of the preallocated ones. This costs more.
If you need just native type, use parseInt. If you need an object, use valueOf.
Also, because of this potential allocation, autoboxing isn't actually good thing in every way. It can slow down things.
valueOf - converts to Wrapper class
parseInt - converts to primitive type
Integer.parseInt accept only String and return primitive integer type (int).
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
Iteger.valueOf accept int and String. If value is String, valueOf convert it to the the simple int using parseInt and return new Integer if input is less than -128 or greater than 127. If input is in range (-128 - 127) it always return the Integer objects from an internal IntegerCache. Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 (for example) we always get the same object.
Iteger.valueOf(200)
will give new Integer from 200. It's like new Integer(200)
Iteger.valueOf(127)
is the same as Integer = 127
;
If you wont to convert String to the Integer use Iteger.valueOf
.
If you wont to convert String to the simple int use Integer.parseInt
. It works faster.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
And comparing Integer.valueOf(127) == Integer.valueOf(127) return true
Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
a == b; // return true
Because it takes the Integer objects with the same references from the cache.
But Integer.valueOf(128) == Integer.valueOf(128) is false, because 128 is out of IntegerCache range and it return new Integer, so objects will have different references.
The parse* variations return primitive types and the valueOf versions return Objects. I believe the valueOf versions will also use an internal reference pool to return the SAME object for a given value, not just another instance with the same internal value.
If you check the Integer class you will find that valueof call parseInt method. The big difference is caching when you call valueof API . It cache if the value is between -128 to 127 Please find below the link for more information
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Because you might be using jdk1.5+ and there it is auto converting to int. So in your code its first returning Integer and then auto converted to int.
your code is same as
int abc = new Integer(123);
public static Integer valueOf(String s)
The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string. In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s))
In case of ValueOf -> it is creating an Integer object. not a primitive type and not a static method. In case of ParseInt.ParseFloat -> it return respective primitive type. and is a static method.
We should use any one depending upon our need. In case of ValueOf as it is instantiating an object. it will consume more resources if we only need value of some text then we should use parseInt,parseFloat etc.
Success story sharing
Integer.valueOf(Integer.parseInt("123"))
has no benefit overInteger.valueOf("123")
orInteger.valueOf(123)
aside from wasting cycles and the size of your program.Integer.valueOf(String)
does exactly the same caching asInteger.valueOf(int)
. In fact, it is implemented asInteger.valueOf(Integer.parseInt(…))
…int
. The signature says it returns anInteger
, and that is exactly what it does. This answer is also partially incorrect when it says it returns a 'new'Integer
. That's not what it says in the Javadoc. It is free to return a cachedInteger
.