9

I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt and catching any resulting exception. Another one is by using Pattern. Which of the following is better approach?

String countStr;
int count;
try {
    count = Integer.parseInt(countStr);
} catch (Exception e) {
    //return as the variable is not a proper integer.
    return;
}

or

String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
    //return as the variable is not a proper integer.
    return;
}

My question here is, is doing an Integer.parseInt() and catching an exception for validation a standard way to validate an int? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?

4
  • Your regular expression does not validate negative numbers. Commented Jun 13, 2013 at 11:17
  • Depends on the situation. Commented Jun 13, 2013 at 11:17
  • 2
    what happens if you check "2147483647", "2147483650" or "" with your regex? Commented Jun 13, 2013 at 11:26
  • Btw i think you should rather catch NumberFormatException and not just Exception Commented Jun 13, 2013 at 12:00

4 Answers 4

8

Using the approach above is better as it considers all types of possible errors and handles all cases. For instance what you have written will not parse negative numbers correctly.

It only makes sense to write your own verifier if you want to validate a given subset of all integers.

A general advice: don't re-invent the wheel unless you have strong reasons to do so.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes. My regular expression validates only positive numbers. But is doing an Integer.parseInt() and catching an exception for validation a standard way? Is there any inbuilt methods available for validation?
Yes that is the standard way to validate an integer.
@afxgx Considering that it's almost impossible to write a regex that will handle all cases (2^31 is a perfectly fine integer, but will throw an exception when you try to parse it because it's too big), it's an exceedingly bad idea. A regex that handles all cases is obviously possible, but will be really, really long..
4

There's a really good reason to not go with the second approach if you actually want to check if the given string can be represented as a 32bit integer and not just that it represents an integer in the mathematical sense.

I'm sure we all agree that 2147483648 (2**31 for those paying attention) is a perfectly fine integer, but it's only one of infinitely many numbers for which the two options will give different results. So if you want to check if you can represent a string as a 32bit integer use the parseInt method, if you just want to see if it's an integer go with the regex.

PS: That said don't catch Exception, but the correct NumberFormat exception instead..

3 Comments

@Marco Sorry but I really don't see your point?
max value is 2^31-1 and not 2^31
@Marco I'd hope so, after all the whole point is to find a value that can't be represented as an int.
3

These two function serve different purposes. If you just want to make sure that the string cotains a particular pattern, then use the second approach. If you need to convert it, then you should can parseInt() In this case it wouldn't make sense to check it and convert it as well.

However, if you have specific requirements for the number, then you may have to check it first regardless, because parseInt() may not always throw an exception if it can parse something which still doesn't fit your requirement.

Comments

-1

If you just validat an Integer, I think the second way is better.

These two methods both will work fine, but obviously different focus. The former focuses on the transformation itself, while the latter is clearly more attention checked. And you want to check a number is, so I think the second method is better. Also, I think, some of the second method more readable, allowing code maintenance is a clear to see, where the logic is in checking the validity of a number instead of a string into a number.

1 Comment

Except that just because the regex returns true doesn't mean you can actually represent it as a 32bit integer..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.