Here you can find the source of toByte(String str)
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
Parameter | Description |
---|---|
str | the string to convert, may be null |
zero
if conversion fails
public static byte toByte(String str)
//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; } } }