Monday, March 23, 2009

How to check if a Java String is an integer?

Use static method Integer.parseInt() and catch the exception that is thrown when the number cannot be parsed.


String s = "123";
boolean isValidInteger = false;
try
{
int i = Integer.parseInt(s);

// s is a valid integer

isValidInteger = true;
}
catch (NumberFormatException ex)
{
// s is not an integer
}

1 comment:

Anonymous said...

Test Comment