Does java have int.tryparse that does not throw an exception for bad data?

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

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

The great thing about this method is that it does not throw an exception for bad data.

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

Is there any way around this somehow for those cases where performance is a problem?

The only other way I can come up with is to run regex input, but I have to check to see which is faster.

+97
java
Dec 05 '11 at
source share
3 answers

No. You have to make your own like this:

 boolean tryParseInt(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } 

... and you can use it like this:

 if (tryParseInt(input)) { Integer.parseInt(input); // We now know that it safe to parse } 

EDIT (based on @Erk comment)

Something like the following should be better

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

If you overload this with a method with one string parameter, it will be even better, which will allow you to use it with a default value, which is optional.

 public int tryParse(String value) { return tryParse(value, 0) } 
+51
Dec 05 2018-11-21T00:
source share

Apache Commons has an IntegerValidator class that seems to do what you want. Java does not provide a built-in method for this.

+27
Dec 05 2018-11-21T00:
source share

Edit - just looked through your comment about performance issues related to a potentially poor amount of input. I don't know how try / catch on parseInt compares with regex. I would suggest that, based on very little knowledge, regular expressions are not very efficient compared to try / catch in Java.

Anyway, I would 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; } 
0
Dec 05 '11 at
source share



All Articles