一、基本类型有几种,各占字节多少
类型 | 字节 | 默认值 |
---|---|---|
byte | 1 | 0 |
short | 2 | 0 |
int | 4 | 0 |
long | 8 | 0L |
float | 4 | 0f |
double | 8 | 0d |
char | 2 | ‘u0000’ |
boolean | 1 | false |
注意:
长整型long 必须加L后缀,否则会被当成整型int处理。
二、包装类型有哪些
这八种基本类型都有对应的包装类分别为:Byte、Short、Integer、Long、Float、Double、Character、Boolean 。
三、装箱与拆箱
Integer x=Integer.valueOf(100); 装箱 (等价于Integer x = 100)
int i = x.intValue(); 拆箱 (等价于int i = x)
Java 基本类型的包装类的大部分都实现了常量池技术。Byte,Short,Integer,Long 这 4 种包装类默认创建了数值 [-128,127] 的相应类型的缓存数据,Character 创建了数值在[0,127]范围的缓存数据,Boolean 直接返回 True Or False。
Integer 缓存源码:
/**
*此方法将始终缓存-128 到 127(包括端点)范围内的值,并可以缓存此范围之外的其他值。
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
}
注意:
pojo类成员变量选择使用包装类型。
(1)基本类型有默认值,传空会导致看不出错误(0 和null是两个概念)
(2)参数为空验证由自己验证,提高非法传入空值警觉性
包装类缓存是装箱是进行缓存,在范围进行对象复用,不在范围则进行创建新对象,所以包装类值比较使用equals比较。
数相等equals比为true,==则不一定。