Difference between valueOf and parseInt method in Java

Both valueOf and parseInt methods are used to convert String to Integer in Java, but there are subtle difference between them. If you look at code of valueOf() method, you will find that internally it calls parseInt() method to convert Integer to String, but it also maintains a pool of Integers from -128 to 127 and if requested integer is in pool, it returns object from pool. Which means two integer objects returned using valueOf() method can be same by equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collector. Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns an Integer 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.
Read more »

0 Response to "Difference between valueOf and parseInt method in Java"

Posting Komentar