Java的八种基本数据类型对应的包装器类分别为:Byte,Short,Character(char类型),Integer(int型),Long,Float,Double, Boolean。(默认值为null)
创建包装器类型对象的两种方式:
包装器类型对象共同的特点:
对象一旦赋值,其值不能再改变。
// 对象指向的变量的值不能改变,但可以指向其他变量
Character c1 = Character.valueOf('a'); Character c2 = Character.valueOf('b'); System.out.println(c1+":"+c2); c2 = Character.valueOf('c'); System.out.println(c2); c2 = 'd'; System.out.println(c2);
打印结果:
Character c1=Character.valueOf('a'); System.out.println(c1.charValue());
打印结果:a
在Java中一些运算或程序对数据类型是有限制的,比如:++/–操作符只能操作基本类型数据,集合中只能存放包装器类型对象等等。
Integer y = new Integer (1); int x = y.intValue(); System.out.println(x); x++; y = new Integer(x); System.out.println(y);
打印结果为:1 2
Integer y = new Integer (1); y++; System.out.println(y);
打印结果为:2
// y++之前和之后所引用的内存地址不同
基本数据类型会被加宽到更宽泛的基本数据类型
例:short s1=5; //将5加宽成整形
基本数据类型和对应的包装器类型是不同的数据类型
选择重载时匹配哪个方法时遵循以下原则:
包装器类型和String类型对equals方法进行重写,判断值是否相同,其他类的equals和==没有区别,都是比较地址是否相同