This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Trying to check the given String value is a integer. The given String value is a integer "1001234578999" but throwing a number format exception. Can some one shed some light why its throwing number format exception.
String s = "1001234578999";
long i = Long.parseLong(s);
System.out.println("long value is ::>>"+i);
catch (NumberFormatException nfe)
System.err.println("s is not parseable as an integer");
When parsing Strings of variable (potentially large values) it's better to use Long.parseLong() method to avoid the NumberFormatException:
You might want to wrap it in a try/catch block as well because if the String happens to have a non-numerical character it will throw the same exception.
Joined: Nov 06, 2000
(Pradad didn't say he needed to parse the string -- he said he needed to check whether it was an integer. Parsing it, and using exception handling as a way of testing whether it worked, seems to be an awkward way to do that test. If the ultimate goal is to convert it to a numeric value, then we need more information -- perhaps BigInteger is the best way to handle the value?)