Search code examples
javastringintegerdefault-valueparseint

How can I parse String to int with the default value?


I need to parse a string user id into integer for that I used Integer.parseInt(String s) but it returns null/nil, if there string has/holds non-decimal/integer value and in that case, I need to assign default integer value as 0.

I tried this but it (? 0) seems not working and I don't know whether it is correct syntax or not.

String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;

How can assign default value to integer if there is null assignment?

String userid is a parameter argument as part of web service function call, so I cannot update it's data type to integer.


Solution

  • You're most likely using apache.commons.lang3 already:

    NumberUtils.toInt(str, 0);