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

You can use this way with String::matches like this :

String userid = "user001";
int int_userid = userid.matches("\\d+") ? Integer.parseInt(userid) : 0;

You ca also use -?\d+ for both positive and negative values :

int int_userid = userid.matches("-?\\d+") ? Integer.parseInt(userid) : 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!


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

NumberUtils.toInt(str, 0);