Search code examples
javastringparseint

Proper way to avoid parseInt throwing a NumberFormatException for input string: ""


When I run parseInt:

Integer.parseInt(myString);

it throws:

NumberFormatException: For input string: ""

Does this mean I have do something like this?

if(StringUtils.isNotBlank(myString))
  return Integer.parseInt(myString);
else
 return 0;

Solution

  • Well, you could use the conditional operator instead:

    return StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
    

    If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where myString is null, or contains non-numeric text.