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