Java基本数据类型及其包装类
| 基本类型 | 大小 | 默认值 | 最小值 | 最大值 | 包装器类型 | 缓冲池范围 |
|---|---|---|---|---|---|---|
| boolean | —— | false | —— | —— | Boolean | true,false |
| char | 2字节 | ‘u0000’ | Unicode 0 | Unicode 216 -1 | Character | \u0000 ~ \u007F |
| byte | 1字节 | 0 | -128 | 127 | Byte | -128~127 |
| short | 2字节 | 0 | -215 | 215-1 | Short | -128~127 |
| int | 4字节 | 0 | -231 | 231 -1 | Integer | -128~127 |
| long | 8字节 | 0L | -263 | 263 - 1 | Long | -128~127 |
| float | 4字节 | 0f | -231 | 231 -1 | Float | 无缓冲池 |
| double | 8字节 | 0d | -263 | 263 - 1 | Double | 无缓冲池 |
1. 数据定义中需要注意的问题
Java 中的 long 为啥要加 L,float 要加 f,而 double 不需要加 d?
- Java 中默认整数类型用 int 接收,浮点型用 double 接收
- …
public class Test {
public static void main(String[] args) {
//float类型数据定义需要加 f(或 F)
float f = 1.0f;
//double类型数据定义可以不加 d(或 D)
double d = 1.0;
//long类型数据定义必须加 L,否则将当做 int 解析
long l = 12345678912L;
}
}
Java 不能隐式地向下转型,因为这会使精度降低。
复合赋值的规定:E1 op= E2等价于 E1=(T)(E1 op E2),自动进行隐式类型转换
public class Test {
public static void main(String[] args) {
short a = 1;
// a = a + 1; // 错误
short b = 1;
b++; //正确
b += 1; //正确
short c = 1;
short d = 2;
// short f = c + d; //错误
short e = (short)(c + d); //正确
}
}
2. 为什么提供包装类?
让基本数据类型具备对象的特征,实现更多的功能,例如在使用集合时就必须用包装类型
3. 缓冲池
Java 基本数据类型的包装类大部分实现了常量池技术,例如,在常量池中 Integer 已经默认创建了数值 [-128, 127]的 Integer 缓存数据。在使用这些基本数据类型的包装类型时,如果该数值的范围在缓冲池范围内,则直接使用缓冲池中的对象,如果超出范围,则创建新的对象。
注意:float 和 double 的包装类无缓冲池,因为浮点数的个数无限
Integer 的缓冲池比较特殊,可以在 JVM 启动的时候设置最大值(–XX:AotoBoxCacheMax=)
4. 装箱与拆箱
装箱:自动将基本数据类型转换为包装类型
拆箱:自动将包装类型转换为基本数据类型
public class Test {
public static void main(String[] args) {
//无法触发装箱和拆箱,会创建新的对象
Integer m = new Integer(100);
//装箱,Java在编译时将代码封装成 Integer i = Integer.valueOf(100);
Integer i = 100;
//拆箱,Java在编译时将代码封装成 int j = i.intValue();
int j = i;
}
}
5. 包装类比较大小
- 对于包装类型,equals方法并不会进行类型转换
- == 如果左右不存在运算符,则比较引用地址,存在运算符则比较数值大小(即拆箱)
public class Test {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
System.out.println(e == f); //false 比较地址,超过缓冲池范围,创建新的对象,所以地址不同
System.out.println(c == a + b); //true 比较数值
System.out.println(g.equals(a+b)); //false Long 和 Integer
}
}


被折叠的 条评论
为什么被折叠?



