Search

Tuesday, August 25, 2015

2 ways to parse String to int in Java

Java provides Integer.parseInt() method to parse a String to an int value, but that's not the only way to convert a numeric String to int in Java. There is in fact a better way, which take advantage of parsing logic of parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about Integer.valueOf() method, which implements Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127. So every time you pass a numeric String which is in range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but return the same value from cached pool. Only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to int value in Java. BTW, if you are learning Java and want to master fundamentals, I suggest you to take a look at Head First Java 2nd Edition, they explains the concept in the easiest way possible but also brings out important details.

Read more »

No comments:

Post a Comment