Does java have a int.tryparse that doesn't throw an exception for bad data?

Java

Java Problem Overview


> Possible Duplicate:
> Java: Good way to encapsulate Integer.parseInt()
> how to convert a string to float and avoid using try/catch in java?

C# has Int.TryParse: Int32.TryParse Method (String, Int32%)

The great thing with this method is that it doesn't throw an exception for bad data.

In java, Integer.parseInt("abc") will throw an exception, and in cases where this may happen a lot performance will suffer.

Is there a way around this somehow for those cases where performance is an issue?

The only other way I can think of is to run the input against an regex, but I have to test to see what is faster.

Java Solutions


Solution 1 - Java

No. You have to make your own like this:

public int tryParseInt(String value, int defaultVal) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultVal; } }

...or

public Integer parseIntOrNull(String value) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return null; } }

Solution 2 - Java

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

Code sample: (slightly verbose to show functionality clearly)

private boolean valueIsAndInt(String value) {
    boolean returnValue = true;
    if (null == new org.apache.commons.validator.routines.IntegerValidator().validate(value)) {
        returnValue = false;
    }
    return returnValue;
}

Solution 3 - Java

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodecompletingView Question on Stackoverflow
Solution 1 - JavaWoot4MooView Answer on Stackoverflow
Solution 2 - JavaGraham BorlandView Answer on Stackoverflow
Solution 3 - JavaJim KileyView Answer on Stackoverflow