24
\$\begingroup\$

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) { }
\$\endgroup\$

7 Answers 7

25
\$\begingroup\$

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.

\$\endgroup\$
1
  • 5
    \$\begingroup\$ +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. \$\endgroup\$ Dec 19, 2012 at 14:09
25
\$\begingroup\$

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.)

\$\endgroup\$
1
  • 3
    \$\begingroup\$ excellent suggestion! I am very thankful for the Apache Commons libraries. \$\endgroup\$
    – janoulle
    Sep 19, 2017 at 16:56
8
\$\begingroup\$

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;
  }
}
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Hungarian notation is really not necessary... \$\endgroup\$
    – assylias
    Dec 24, 2012 at 19:37
  • \$\begingroup\$ @assylias : Well, it is only necessary in order to maintain a high level of pedanticism... :-) \$\endgroup\$ Jan 3, 2013 at 0:41
  • \$\begingroup\$ It does not compile (Cannot convert from null to int). \$\endgroup\$
    – palacsint
    Jan 8, 2013 at 22:16
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Jan 8, 2013 at 22:32
1
\$\begingroup\$

Parsing Methods in Java Convert String to Int

In Java there are two methods to convert String to Int, they are:

Integer.parseInt()
Integer.valueOf()
  1. Convert String to Int using Integer.parseInt() The Integer.parseInt() is a static method of Integer class used in Java to converts string to primitive integer.

Example:

String ‘100’ to primitive integer 100

Note:Parsing is a process of converting one data type to another. For example String to integer. Coding part please refer this: best way to convert string to int

\$\endgroup\$
1
\$\begingroup\$

The performance cost of creating and throwing an Exception in Java can, and normally always is significantly more taxing than pre-validating a value can be converted. For all JVM's I am aware of (IBM's Java, Oracle's Java, OpenJDK, etc.) the cost of the exception also often linearly scales relative to the depth of the call stack when the exception is thrown, so deeply-nested exceptions are more costly than exceptions in the main-method....

The bottom line is that in good code you should never (with very few exceptions) make exceptions part of the normal/expected flow of the code.

So, in your case, I would minimalize the possibility of exceptions by trying as hard as reasonable to eliminate exception cases, while still handling the exceptions appropriately.

Note that the documentation for Double.valueOf(String) alludes to this and also provides a regular expression useful for checking whether valueOf may throw an exception.

private static final Pattern isInteger = Pattern.compile("[+-]?\\d+");

public static final int tryParseInt(String value) {
    if (value == null || !isInteger.matcher(value).matches()) {
        return 0;
    }
    try {  
        return Integer.parseInt(value);  
    } catch(NumberFormatException nfe) {  
        return 0;
    }  
}

While the additional checks may slow down valid numbers slightly, it drastically improves the performance of handling invalid numbers in the majority of the cases, and the trade-off is, in my experience more than worth it.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.