I am searching for a method to check if it is possible to convert a string to int.
The following link says that it is not possible but since new Java version are available I would like to check.
I am searching for a method to check if it is possible to convert a string to int.
The following link says that it is not possible but since new Java version are available I would like to check.
 
    
     
    
    You may wish to consider the NumberUtils.isDigits method from Apache Commons. It gives a boolean answer to the question and is null safe.
For a broader range of numbers that could include decimal points such as float or double, use NumberUtils.isParsable.
 
    
    Java 8 does not change anything by the type parsing. So you still have write your own typeParser like this:
public Integer tryParse(String str) {
  Integer retVal;
  try {
    retVal = Integer.parseInt(str);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}
 
    
    It is not a good idea to use exceptions to control flow - they should only be used as exceptions.
This is a classic problem with a regex solution:
class ValidNumber {
    // Various simple regexes.
    // Signed decimal.
    public static final String Numeric = "-?\\d*(.\\d+)?";
    // Signed integer.
    public static final String Integer = "-?\\d*";
    // Unsigned integer.
    public static final String PositiveInteger = "\\d*";
    // The valid pattern.
    final Pattern valid;
    public ValidNumber(String validRegex) {
        this.valid = Pattern.compile(validRegex);
    }
    public boolean isValid(String str) {
        return valid.matcher(str).matches();
    }
}
