Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {

    try {

        Integer.parseInt( input );

        return true;

    }

    catch( Exception e ) {

        return false;

    }

}

Is it just me, or does this seem a bit hackish? What's a better way?

1 Answer

0 votes
by (46k points)

If you are not involved with potential overflow difficulties this function will make about 20-30 times more durable than using Integer.parseInt().

public static boolean isInteger(String str) {

    if (str == null) {

        return false;

    }

    int length = str.length();

    if (length == 0) {

        return false;

    }

    int i = 0;

    if (str.charAt(0) == '-') {

        if (length == 1) {

            return false;

        }

        i = 1;

    }

    for (; i < length; i++) {

        char c = str.charAt(i);

        if (c < '0' || c > '9') {

            return false;

        }

    }

    return true;

}

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...