20

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;
Mocktagish
  • 291
  • 1
  • 4
  • 8

7 Answers7

32

Yes, but: Wrap it in a thin method (and eliminate the redundant else), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue):

NumberUtils.toInt(myString, 0);

This method handles null values and conversion failures.

Writing the same thing on your own is straight-forward:

  • Check for null, and/or...
  • ...Wrap the NumberFormatExtension exception
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
24

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

If the string can be empty I do it this way:

Integer.parseInt("0" + inputString)

When I'm not sure it contains only digits:

Integer.parseInt(0 + inputString.replaceAll("\\D+",""))
Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54
4

What you have is fine, but as a coding style I prefer to make tests "positive" (isBlank), rather than "negative" (isNotBlank), ie

if (StringUtils.isBlank(myString)) {
    return 0;
}
return Integer.parseInt(myString); // Note: No need for else when the if returns

or, more succinctly:

return StringUtils.isBlank(myString) ? 0 : Integer.parseInt(myString);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

I don't know why was I searching for this but here's the easy way:

int test=str.isEmpty()?0:Integer.parseInt(str);
gndp
  • 231
  • 2
  • 12
0

Yes. (Validate your inputs before making assumptions about what are in them. :-)

+1 for already finding Apache's common-lang w/ StringUtils.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
0

Integer.parseInt(String) doesn't accept non-numeric input, including nulls and empty strings.

Either guard against that like you suggested, or catch the NFE.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Dan Hardiker
  • 3,013
  • 16
  • 19