Java - Write code to Convert a string to an int value.

Requirements

Write code to Convert a string to an int value.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        int defaultValue = 42;
        System.out.println(convertStrToInt(string, defaultValue));
    }//from   ww w.  j a v a 2  s  .c  o m

    /**
     * Convert a string to an int value.  If an error occurs during the conversion,
     * the default value is returned instead.  Unlike the {@link Integer#parseInt(String)}
     * method, this method will not throw an exception.
     *
     * @param string       value to test
     * @param defaultValue value to return in case of difficulting converting.
     * @return the int value contained in the string, otherwise the default value.
     */
    public static int convertStrToInt(final String string,
            final int defaultValue) {
        if (string == null) {
            return defaultValue;
        }

        try {
            return Integer.parseInt(string);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}

Related Exercise