Let’s consider the following code snippet in Java. There are some of possible approaches (that I know) to parse a String value to other numeric types (Let’s say for the sake of simplicity, it is an Integer, a wrapper type in Java).
package parsing;
final public class Parsing
{
public static void main(String[] args)
{
String s="100";
Integer temp=new Integer(s);
System.out.print("\ntemp = "+temp);
temp=Integer.parseInt(s);
System.out.print("\ntemp = "+temp);
temp=Integer.valueOf(s).intValue();
System.out.print("\ntemp = "+temp);
temp=Integer.getInteger(s);
System.out.print("\ntemp = "+temp);
}
}
In all the cases except the last one, returns the value 100 after converting it into an Integer. Which one is the best approach to parse a String value to other numeric types available in Java? The last case returns NULL even if the String object s already contains a parsable value. Why?
Calling
Integer.getInteger("42")attempts to fetch the value of the system property whose name is “42”. Unless you really do have a system property with that name, it will returnnull.Here is the Java 7 javadoc if you want more details.
Yes, the name of the method is misleading, and its utility is questionable.
FWIW, I’d use
Integer.parseInt(String)if I required anintresult andInteger.valueOf(String)if I required anInteger. I’d only usenew Integer(String)if I required the object to be a newIntegerand not one that might be shared.(The reasoning is the same as for
new Integer(int)versusInteger.valueOf(int). Again, read the javadocs for a more complete explanation.)