String to Int in java – Likely bad data, need to avoid exceptions

I asked if there were open source utility libraries that had methods to do this parsing for you and the answer is yes!

From Apache Commons Lang you can use NumberUtils.toInt:

// returns defaultValue if the string cannot be parsed.
int i = org.apache.commons.lang.math.NumberUtils.toInt(s, defaultValue);

From Google Guava you can use Ints.tryParse:

// returns null if the string cannot be parsed
// Will throw a NullPointerException if the string is null
Integer i = com.google.common.primitives.Ints.tryParse(s);

There is no need to write your own methods to parse numbers without throwing exceptions.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)