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?

Bogdan Kobylynskyi
  • 1,150
  • 1
  • 12
  • 34
  • 3
    have you considered regex? – Stultuske Nov 17 '15 at 13:08
  • 2
    the code you posted is very bad, since it "abuses" Exception Handling – Stultuske Nov 17 '15 at 13:10
  • 1
    I find this solution quite beautiful. And why oh earth should it "abuse" Exception Handling? – Mario A Nov 17 '15 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). – Tunaki Nov 17 '15 at 13:13
  • Do you call something like 1.0 an integer? – Bathsheba Nov 17 '15 at 13:13
  • ... and this question is the n'th duplicate of [What's the best way to check to see if a String represents an integer in Java?](http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java) (or even [Determine if a String is an Integer in Java](http://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java)) or ... – Seelenvirtuose Nov 17 '15 at 13:16
  • 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). – Seelenvirtuose Nov 17 '15 at 13:18
  • @Seelenvirtuose: As the exception is thrown by Integer.parseInt() I would consider it an exceptional case. – Mario A Nov 17 '15 at 13:27
  • @MarioA Exactly! And the case that a string does _not_ represent an integer is a _normal_ execution flow for the question that this method shall answer. – Seelenvirtuose Nov 17 '15 at 13:50

2 Answers2

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.

Niels Billen
  • 2,189
  • 11
  • 12
3

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

private boolean isInt(String string) {
    return string.matches("-?\\d+");
}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • 1
    This introduces a subtle bug: a Long would match whereas the code in the OP's question would not. – Tunaki Nov 17 '15 at 13:11
  • 1
    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}");`. – ThomasThiebaud Nov 17 '15 at 13:23