Java - Write code to Convert a string to a long value.

Requirements

Write code to Convert a string to a long value.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        long defaultValue = 42;
        System.out.println(convertStrToLong(string, defaultValue));
    }/*w  w  w . j  a  va 2  s  . co m*/

    /**
     * Convert a string to a long 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 long convertStrToLong(final String string,
            final long defaultValue) {
        if (string == null) {
            return defaultValue;
        }

        try {
            return Long.parseLong(string);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}