Parse string to int, return defaultValue if parse fails - Java java.lang

Java examples for java.lang:String Parse

Description

Parse string to int, return defaultValue if parse fails

Demo Code



public class Main{
    public static void main(String[] argv){
        String value = "java2s.com";
        int defaultValue = 42;
        System.out.println(parseInteger(value,defaultValue));
    }/* w  ww.j  a va 2s  . c  o m*/
    /** Parse string to int, return defaultValue if parse fails */
    public static int parseInteger(String value, int defaultValue) {
        int parsed = defaultValue;
        if (value != null) {
            try {
                parsed = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                parsed = defaultValue;
            }
        }
        return parsed;
    }
}

Related Tutorials