Check a String Is a Valid Integer in Java
In this Java core tutorial, we learn how to check if a String value is a valid integer value or not in Java program.
Implement isValidInteger() method
In the following Java code, we implement a method to check if a given String is a valid integer or not and return the result in boolean value.
The method uses Java’s Integer.parseInt() static method to try to parse the String value, in case it is the invalid integer String the Exception throws then our method returns false value.
public static boolean isValidInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (Exception ex) {
return false;
}
}
The following complete Java program uses the method above to check different String values and print the result.
CheckValidIntegerExample.java
public class CheckValidIntegerExample {
public static void main(String[] args) {
boolean result1 = isValidInteger("-10");
boolean result2 = isValidInteger("+10");
boolean result3 = isValidInteger("10");
boolean result4 = isValidInteger("ABC");
boolean result5 = isValidInteger("1A");
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
System.out.println(result4);
System.out.println(result5);
}
public static boolean isValidInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (Exception ex) {
return false;
}
}
}
true
true
true
false
false
Happy Coding 😊
Related Articles
Validate Email Address in Java