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

后端 未结 30 1451
野趣味
野趣味 2020-11-22 05:45

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

public boolean isInteger( String input ) {
    try {
        Integer.         


        
30条回答
  •  礼貌的吻别
    2020-11-22 06:36

    I have seen a lot of answers here, but most of them are able to determine whether the String is numeric, but they fail checking whether the number is in Integer range...

    Therefore I purpose something like this:

    public static boolean isInteger(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            long value = Long.valueOf(str);
            return value >= -2147483648 && value <= 2147483647;
        } catch (Exception ex) {
            return false;
        }
    }
    

提交回复
热议问题