创建Byte对象,报错:Exception in thread “main” java.lang.NumberFormatException: For input string: “xxx”

在使用Byte构造方法创建一个Byte对象时,报错如下:

Exception in thread "main" java.lang.NumberFormatException: For input string: "itzhimei"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Byte.parseByte(Byte.java:149)
	at java.lang.Byte.<init>(Byte.java:316)
	at com.itzhimei.base.j2se.lang.ByteTest_1.main(ByteTest_1.java:7)

代码:

public class ByteTest_1 {

    public static void main(String[] args) {
        System.out.println("Min:" + Byte.MIN_VALUE + ",Max:" + Byte.MAX_VALUE);
        Byte b1 = new Byte("itzhimei");
        System.out.println(b1);
    }
}

问题原因:
这里的构造方法支持使用字符串进行初始化:public Byte(String s)

再看源码:

public Byte(String s) throws NumberFormatException {
	this.value = parseByte(s, 10);
}

public static byte parseByte(String s, int radix)
	throws NumberFormatException {
	int i = Integer.parseInt(s, radix);
	if (i < MIN_VALUE || i > MAX_VALUE)
		throw new NumberFormatException(
			"Value out of range. Value:\"" + s + "\" Radix:" + radix);
	return (byte)i;
}

源码中是将构造方法的参数,转换成一个Integer类型,然后强转为byte类型,并且还判断了这个参数转换为Integer后的大小是否在byte的最大最小值范围内。
一个Byte类型的值的范围:Min:-128,Max:127,因为byte只有一个字节的存储空间,且是有符号的,所以大家可以自己算一下,其取值就是-128到127之间,所以Byte的构造方法参数要能转换为数字且要符合byte的取值范围,如果不满足,就会报上面的错。

解决办法:构造方法参数正确赋值即可。