Here you can find the source of toInt(String str, int defaultValue)
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
Parameter | Description |
---|---|
str | the string to convert, may be null |
defaultValue | the default value |
public static int toInt(String str, int defaultValue)
//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; } } }