Bill the Lizard Bill the Lizard - 4 years ago 130
Java Question

What's the best way to check to see if a String represents an integer in Java?

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?




See my answer (with benchmarks, based on the earlier answer by CodingWithSpike) to see why I've reversed my position and accepted Jonas Klemming's answer to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.

Answer Source

If you are not concerned with potential overflow problems this function will perform about 20-30 times faster 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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download