# Convert String to Integer with default value

I want to convert a java.lang.String to a java.lang.Integer, assigning a default value of 0 if the String is not convertible. Here is what I came up with. I would appreciate an assesment of this approach.

To be honest, it feels a little squirrely to me:

String strCorrectCounter = element.getAttribute("correct");
Integer iCorrectCounter = new Integer(0);
try {
iCorrectCounter = new Integer(strCorrectCounter);
} catch (Exception ignore) { }

-

here is a solution :

int tryParseInt(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException nfe) {
// Log exception.
return 0;
}
}


you should catch NumberFormatException instead of exception.

-
+1 for catching the correct exception and using parseInt() so a cached Integer can be returned instead of guaranteeing that a new instance is returned. –  unholysampler Dec 19 '12 at 14:09

I'd consider using NumberUtils.toInt from Apache Commons Lang which does exactly this:

public static int NumberUtils.toInt(java.lang.String str, int defaultValue)


The implementation uses the already mentioned Integer.parseInt with an additional null check.

See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)

-

As others have noted, your code should never catch Exception. Doing so causes all sorts of problems. In addition to the answers given I would also suggest that you don't default the value to 0 but make it more generic. For example

public static int parseInteger( String string, int defaultValue ) {
try {
return Integer.parseInt(string);
}
catch (NumberFormatException e ) {
return defaultValue;
}
}

-

You should not use new Integer( string ) instead use Integer.valueOf( string ). As discussed before in many other threads, valueOf may be faster due to the fact it can lookup small integer values and reduces the overhead of creating a new object.

-

Just to be a bit(?) pedantic:

public static final int iDEFAULT_DEFAULT_PARSED_INT = 0;

public static int ifIntFromString( String sToParse) {
return ifIntFromString( sToParse, iDEFAULT_DEFAULT_PARSED_INT );
}

public static int ifIntFromString( String sToParse, int iDefaultValue ) {
int iReturnValue = null;
try {
iReturnValue = Integer.parseInt(sToParse);
} catch ( NumberFormatException e ) {
iReturnValue = iDefaultValue;
}
assert (null != iReturnValue) : "Impossible - no return value has been set!";
return iReturnValue;
}


It would be really great if there were a way to accomplish this without having to catch an exception (due to performance concerns) and without having to write the parsing code yourself - but this is what the base libraries give us.

-
Hungarian notation is really not necessary... –  assylias Dec 24 '12 at 19:37
@assylias : Well, it is only necessary in order to maintain a high level of pedanticism... :-) –  Richard Arnold Mead Jan 3 '13 at 0:41
It does not compile (Cannot convert from null to int). –  palacsint Jan 8 '13 at 22:16
@palacsint Ack! Thanks - bother. Too many languages - my apologies. In Java, null is a first-order token having identity only with itself (if I recall correctly) whereas in many other languages (such as C/C++) it equates to the integer zero. In this instance, my intent was to use null as the "non-value" to indicate a failure to set the variable while still having it be initialized. I ought to have used an Integer object rather than an int type, then converted the Integer to an int for the return value. –  Richard Arnold Mead Jan 8 '13 at 22:32