java string is integer check code example
Example 1: java test if a string is a int
public static boolean isInt(String str) {
try {
@SuppressWarnings("unused")
int x = Integer.parseInt(str);
return true; //String is an Integer
} catch (NumberFormatException e) {
return false; //String is not an Integer
}
}
Example 2: test if string is float java
public static void main(String[] args) {
String str = "5588";
//check if int
try{
Integer.parseInt(str);
}catch(NumberFormatException e){
//not int
}
//check if float
try{
Float.parseFloat(str);
}catch(NumberFormatException e){
//not float
}
}