aspose file tools
The moose likes Beginning Java and the fly likes Check for the given String is a integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check for the given String is a integer" Watch "Check for the given String is a integer" New topic

Check for the given String is a integer

Prasad Velakanti

Joined: Aug 31, 2009
Posts: 1
hi All,

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.

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

[My Blog]
All roads lead to JavaRanch
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

welcome to javaranch Prasad
Abhi Chavi

Joined: Jul 21, 2008
Posts: 2
brother thats a long not a integer..
Deepika Singh

Joined: Oct 10, 2008
Posts: 21

String s = "1001234578999";
try {
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");
Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
Prasad, the number which you are converting is not a integer, the maximum value which Interger supports is Integer.MAX_VALUE.... So that reason exception was thrown in your code.

Check "Deepika Singh" code which is the valid way to parse the big numbers ... i hope this make clear.

My Thoughts :
Try not to become a man of success but rather to become a man of value.
Max Rahder
Ranch Hand

Joined: Nov 06, 2000
Posts: 177
I'd use the org.apache.commons.lang.StringUtils isNumeric(String) method.

StringUtils.isNumeric("1001234578999") returns true.

Jarred Olson
Ranch Hand

Joined: Jul 31, 2009
Posts: 37
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.
Max Rahder
Ranch Hand

Joined: Nov 06, 2000
Posts: 177
(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?)
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 40429
[Pedantic mode]The Strings quoted have all been integers. Maybe not ints.[/Pedantic mode]
I agree. Here's the link:
subject: Check for the given String is a integer