Java Byte Create toByte(String str)

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

Description

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

If the string is null, zero is returned.

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

License

Apache License

Parameter

Parameter Description
str the string to convert, may be null

Return

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

Declaration

public static byte toByte(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  www.  j  a  v a  2 s  .c o  m*/
    * <p>Convert a <code>String</code> to a <code>byte</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.toByte(null) = 0
    *   NumberUtils.toByte("")   = 0
    *   NumberUtils.toByte("1")  = 1
    * </pre>
    *
    * @param str  the string to convert, may be null
    * @return the byte represented by the string, or <code>zero</code> if
    *  conversion fails
    * @since 2.5
    */
    public static byte toByte(String str) {
        return toByte(str, (byte) 0);
    }

    /**
     * <p>Convert a <code>String</code> to a <code>byte</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.toByte(null, 1) = 1
     *   NumberUtils.toByte("", 1)   = 1
     *   NumberUtils.toByte("1", 0)  = 1
     * </pre>
     *
     * @param str  the string to convert, may be null
     * @param defaultValue  the default value
     * @return the byte represented by the string, or the default if conversion fails
     * @since 2.5
     */
    public static byte toByte(String str, byte defaultValue) {
        if (str == null) {
            return defaultValue;
        }
        try {
            return Byte.parseByte(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
}

Related

  1. toByte(String hex)
  2. toByte(String hex)
  3. toByte(String hex)
  4. toByte(String hexStr)
  5. toByte(String hexString)
  6. toByte(String string)
  7. toByte(String string)
  8. toByte(String string)
  9. toByte(String value)