Java - Write code to Checks if a string is an integer.

Requirements

Write code to Checks if a string is an integer.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(isInteger(str));
    }/*from  w  w w. j  a va2 s . co m*/

    /**
     * Checks if is integer.
     *
     * @param str
     *            the str
     * @return true, if is integer
     * @see <a href=
     *      "http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java">
     *      Stackoverflow question on faster options to Integer.parseInt()</a>
     */
    public static boolean isInteger(String str) {
        if (str.isEmpty())
            return false;

        int length = str.length(), 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') {
                if (c != '-') {
                    return false;
                }
            }
        }
        return true;
    }
}

Related Exercise