Difference between valueOf and parseInt method in Java? Example (original) (raw)
Both valueOf and parseInt methods are used to convert String to Integer in Java, but there is subtle differences between them. If you look at the code of valueOf() method, you will find that internally it calls parseInt() method to convert String to Integer, but it also maintains a pool of Integers from -128 to 127 and if the requested integer is in the pool, it returns an object from the pool. This means two integer objects returned using the valueOf() method can be the same by the equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collectors.
Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns anInteger object, while parseInt() method returns an int primitive. Though, after introducing Autoboxing in Java 1.5, this doesn't count as a difference, but it's worth knowing.
ParseInt vs valueOf in Java - Example
If you look code of parseInt() and valueOf() method from java.lang.Integer class, you will find that actual job of converting String to integer is done by parseInt() method, valueOf() just provide caching of frequently used Integer objects, Here is code snippet from the valueOf() method which makes things clear:
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }
This method first calls parseInt() method, in order to convert String to primitive int, and then creates an Integer object from that value. You can see it internally maintains an Integer cache. If primitive int is within range of cache, it returns Integer object from the pool, otherwise, it creates a new object.
public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }
And, if you like to see difference in tabular format here is a nice table to see the difference between valueOf and parseInt method in Java:
There is always confusion, whether to use parseInt() or valueOf() for converting String to primitive int and java.lang.Integer, I would suggest use parseInt() if you need primitive int and use valueOf() if you need java.lang.Integer objects. Since immutable objects are safe to be pooled and reusing them only reduces the load on the garbage collector, it's better to use valueOf() if you need an Integer object.