Java Short Number Create toShort(String str)

Here you can find the source of toShort(String str)

Description

Convert a String to a short, returning zero if the conversion fails.

If the string is null, zero is returned.

 NumberUtils.toShort(null) = 0 NumberUtils.toShort("")   = 0 NumberUtils.toShort("1")  = 1 

License

Open Source License

Parameter

Parameter Description
str the string to convert, may be null

Return

the short represented by the string, or zero if conversion fails

Declaration

public static short toShort(String str) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w w w  . j  a v  a2  s . c  o  m*/
     * <p>Convert a <code>String</code> to a <code>short</code>, returning
     * <code>zero</code> if the conversion fails.</p>
     *
     * <p>If the string is <code>null</code>, <code>zero</code> is returned.</p>
     *
     * <pre>
     *   NumberUtils.toShort(null) = 0
     *   NumberUtils.toShort("")   = 0
     *   NumberUtils.toShort("1")  = 1
     * </pre>
     *
     * @param str  the string to convert, may be null
     * @return the short represented by the string, or <code>zero</code> if
     *  conversion fails
     * @since 2.5
     */
    public static short toShort(String str) {
        return toShort(str, (short) 0);
    }

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

Related

  1. toShort(Object value)
  2. toShort(Object value)
  3. toShort(Object value)
  4. toShort(String input, short defaultValue)
  5. toShort(String numeric)
  6. toShort(String str)
  7. toShort(String str, int maxLen)
  8. toShort(String str, short defaultValue)
  9. toShort(String value)