1

I need to check whether the String is an Integer. And I found such solution:

private boolean isInteger(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Is there a more beautiful and proper way to do this without try/catch clause?

9
  • 3
    have you considered regex? Commented Nov 17, 2015 at 13:08
  • 2
    the code you posted is very bad, since it "abuses" Exception Handling Commented Nov 17, 2015 at 13:10
  • 1
    I find this solution quite beautiful. And why oh earth should it "abuse" Exception Handling? Commented Nov 17, 2015 at 13:12
  • 3
    This question is too broad and opinion-based. There is no such thing as an objectively "more beautiful" code. Only right or wrong. And note that the two given answers are wrong (well, subtely wrong). Commented Nov 17, 2015 at 13:13
  • 1
    @MarioA "And why oh earth should it "abuse" Exception Handling?" => Because exceptions should be used for exceptional cases and not for normal execution flow (Joshua Bloch, Effective Java, Item 57). Commented Nov 17, 2015 at 13:18

2 Answers 2

7

You can try a regex like:

Code

private boolean isInteger(String str) {
    return str.matches("\\-?\\d+");
}

Edit

Thanks @Maloubobola for noting that my first attempt would not parse signed integers.

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

2 Comments

This introduces a subtle bug: a Long would match whereas the code in the OP's question would not.
Tunaki is right. Maybe add additional a Integer MIN/MAX check
3

You can try regex. Here is one for positive and negative numbers

private boolean isInt(String string) {
    return string.matches("-?\\d+");
}

2 Comments

This introduces a subtle bug: a Long would match whereas the code in the OP's question would not.
Right. I did not think about it. Maybe check min/max value, or limit the number of digit. Max value for an integer is 2147483647 which contains 10 digits, so in some case (eg you are sure your integer is not 10 digits long) you can use string.matches("-?\\d{1,9}");.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.