5

I like the suggestion in String to Int in java - Likely bad data, need to avoid exceptions to implement a utility method that parses an int, but returns a default value if the string cannot be parsed.

public static int parseInt(String s, int defaultValue) {
    if (s == null) return defaultValue;
    try {
         return Integer.parseInt(s);
     } catch (NumberFormatException x) {
         return defaultValue;
     }  
}

Is there an existing open source library (from apache commons, or google, for example) that implements this as well as for other data types such as boolean, float, double, long, etc?

2
  • 1
    default is a reserved word. Also, it's probably easier to code this yourself. Commented May 22, 2013 at 18:02
  • Changed the example not to use a reserved word. Commented May 22, 2013 at 18:04

2 Answers 2

17

Apache Commons Lang has the class org.apache.commons.lang3.math.NumberUtils with convenient methods for convert. In another way, you can specify a default value if there is a error. e.g.

NumberUtils.toLong("")         => 0L
NumberUtils.toLong(null, 1L)   => 1L

NumberUtils.toByte(null)       => 0
NumberUtils.toByte("1", 0)     => 1
Sign up to request clarification or add additional context in comments.

1 Comment

Although it does parse without exception, the default value might be undesirable. If that is your case like mine there is the org.apache.commons.validator.routines.LongValidator.validate(String) can also take a pattern and/or Locale.
7

Guava has several tryParse methods that return null on a failed parse, e.g. Ints.tryParse, Floats.tryParse, etc

1 Comment

While these methods don't throw NumberFormatException, it should be noted that if you pass a null String into them, they will throw a NullPointerException rather than just returning null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.