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.
Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
parseInt() The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
The method generally used to convert String to Integer in Java is parseInt() of String class.
Strings can be converted to numbers by using the int() and float() methods. If your string does not have decimal places, you'll most likely want to convert it to an integer by using the int() method.
You're most likely using apache.commons.lang3 already:
NumberUtils.toInt(str, 0);
That syntax won't work for Integer.parseInt()
, because it will result in a NumberFormatException
You could handle it like this:
String userid = "user001";
int int_userid;
try {
int_userid = Integer.parseInt(userid);
} catch(NumberFormatException ex) {
int_userid = 0;
}
Please note that your variable names do not conform with the Java Code Convention
A better solution would be to create an own method for this, because I'm sure that you will need it more than once:
public static int parseToInt(String stringToParse, int defaultValue) {
try {
return Integer.parseInt(stringToParse);
} catch(NumberFormatException ex) {
return defaultValue; //Use default value if parsing failed
}
}
Then you simply use this method like for e.g.:
int myParsedInt = parseToInt("user001", 0);
This call returns the default value 0
, because "user001" can't be parsed.
If you remove "user" from the string and call the method...
int myParsedInt = parseToInt("001", 0);
…then the parse will be successful and return 1
since an int can't have leading zeros!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With