基本数据类型
java中有八种基本数据类型,可以分类成:
- 6种数字类型:byte,short,int,long,float,double
- 1种字符类型:char
- 1中布尔类型:boolean
对应包装类分别为:Byte,Short,Integer,Long,Float,Double,Character,Boolean
基本类型 | 位数 | 字节 | 默认值 |
---|---|---|---|
byte | 8 | 1 | 0 |
short | 16 | 2 | 0 |
int | 32 | 4 | 0 |
long | 64 | 8 | 0L |
float | 32 | 4 | 0f |
double | 64 | 8 | 0d |
char | 16 | 2 | ‘u0000’ |
boolean | 1 | false |
自动装箱与拆箱
- 装箱:将基本类型用它们对应的引用类型包装起来
- 拆箱:将包装类型转化为基本数据类型
Byte,Short,Integer,Long四种包装类默认创建了数值[-128,127]的相对应类型的数值,两种浮点类型的包装类Float和Doubel并没有实现常量池技术
Character创建了数值在[0,127]范围额缓存数据
Boolean直接返回True
或者false
Integer a=127与Integer b =127相等嘛
如果整型字面量的值在-128到127之间,那么自动装箱不会new
新的Integer对象,而是直接引用常量池中的Integer对象,若超出范围a1==b1的结果是false
public static void main(String[] args) {
Integer a = new Integer(3);
Integer b = 3; // 将3自动装箱成Integer类型
int c = 3;
System.out.println(a == b); // false 两个引用没有引用同一对象
System.out.println(a == c); // true a自动拆箱成int类型再和c比较
System.out.println(b == c); // true
Integer a1 = 128;
Integer b1 = 128;
System.out.println(a1 == b1); // false
Integer a2 = 127;
Integer b2 = 127;
System.out.println(a2 == b2); // true
}