Java Integer Create toInt(String str, int defaultValue)

Here you can find the source of toInt(String str, int defaultValue)

Description

Convert a String to an int, returning a default value if the conversion fails.

If the string is null, the default value is returned.

 NumberUtils.toInt(null, 1) = 1 NumberUtils.toInt("", 1)   = 1 NumberUtils.toInt("1", 0)  = 1 

License

Open Source License

Parameter

Parameter Description
str the string to convert, may be null
defaultValue the default value

Return

the int represented by the string, or the default if conversion fails

Declaration

public static int toInt(String str, int defaultValue) 

Method Source Code

//package com.java2s;
/*/*from   w w  w. j  a  v a  2s .  co  m*/
 * Copyright 2009-2012 Evun Technology. 
 * 
 * This software is the confidential and proprietary information of
 * Evun Technology. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with evun.cn.
 */

public class Main {
    public static int toInt(String str) {
        return toInt(str, 0);
    }

    /**
     * <p>Convert a <code>String</code> to an <code>int</code>, returning a
     * default value if the conversion fails.</p>
     *
     * <p>If the string is <code>null</code>, the default value is returned.</p>
     *
     * <pre>
     *   NumberUtils.toInt(null, 1) = 1
     *   NumberUtils.toInt("", 1)   = 1
     *   NumberUtils.toInt("1", 0)  = 1
     * </pre>
     *
     * @param str  the string to convert, may be null
     * @param defaultValue  the default value
     * @return the int represented by the string, or the default if conversion fails
     * @since 2.1
     */
    public static int toInt(String str, int defaultValue) {
        if (str == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
}

Related

  1. toInt(String str)
  2. toInt(String str)
  3. toInt(String str)
  4. toInt(String str)
  5. toInt(String str, int defaultValue)
  6. toInt(String str, int defValue)
  7. toInt(String str, int val)
  8. toInt(String string)
  9. ToInt(String string)