Java数据类型和自动拆箱
愚见
- 整型 默认类型为 int
- 浮点型 默认类型为 double
- 在混合多种数据类型的表达式中,类型会向容量大的值的数据类型提升
- long + int/shot/byte = long
- shot/byte + shot/byte = int
- float + float = float
- float/double + double = double
- 1 字节(byte) = 8 位(bit)
- 封装类型 通过 ±*/ 运算时,会自动拆箱
10.封装类型和基本数据类型 == 比较时,会自动拆箱
Java 数据类型
数值型 | 内存大小 | 取值范围 |
---|---|---|
byte | 1字节 * 8 = 8 位 | (-2^8/2) ~ (2^8/2) - 1 |
shot | 2字节 * 8 = 16 位 | (-2^16/2) ~ (2^16/2) - 1 |
int | 4字节 * 8 = 32 位 | (-2^32/2) ~ (2^32/2) - 1 |
long | 8字节 * 8 = 64 位 | (-2^64/2) ~ (2^64/2) - 1 |
float | 4字节 * 8 = 32 位 | -3.403E38~3.403E38 |
double | 8字节 * 8 = 64 位 | -1.798E308~1.798E308 |
char | 2字节 * 8 = 16 位 | |
boolean |
前置知识点
instanceof 判断变量类型
基本数据类型无法使用 instanceof;当 用Object 接收 基本数据类型时,基本数据类型的变量 会自动装箱
public static void main (String[] args){
int i = 3 ;
test6(i);
}
private static void test6(Object integer) {
System.out.println(integer instanceof Integer); //true
}
封装类型的equals()方法
equals() 方法首先会判断 类型,然后 判断值 是否相等
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
自动拆箱
拆箱装箱原理
自动装箱隐式调用 Integer.valueOf(int) 方法;-128< int <127 时,返回缓存池里面的对象 ,不在范围里时才创建对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
直接new 对象时不会自动装箱,不会调用 Integer.valueOf(int)
public static void main (String[] args){
Integer i0 = 1 ;
Integer i1 = new Integer(1);
Integer i2 = Integer.valueOf(1) ; ;
System.out.println(i0 == i1);//false
System.out.println(i0 == i2);//true
}
自动拆箱隐式调用 integer.intValue()方法;
public int intValue() {
return value; //返回的 this.value 是 integer对象的值int
}
public static void main (String[] args){
Integer i = 3;
Long i1 = 3L ;
long i2 = 3L ;
System.out.println(i.equals(3)); //true
System.out.println(i1.equals(i2)); //true
System.out.println(i1.equals(3)); //false 类型不同
封装类型常见比较
- 封装类型 == 封装类型 ;true 封装类型比较(Integer integer = 1;)
- 封装类型 == 封装类型 ;false 封装类型比较(Integer integer = 128;)
- 封装类型 == 封装类型 ;false 封装类型比较(Integer integer = new Integer (1);)
- 封装类型 == 基本类型 :true 封装类型与基本数据类型 比较时 自动拆箱
- 封装类型 + 封装类型 = 基本数据类型 (封装类型 运算时 会自动拆箱)
- equals() 为true 的条件是:类型相同且值相同
public class Main {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
Long h = 2L;
Integer i1 = new Integer(1);
Integer i2 = new Integer(321);
int i3 = 321 ;
System.out.println(c==d); //true [-128~127]
System.out.println(e==f); //false
System.out.println(c==(a+b)); // true 封装类型 + 号运算时,自动拆箱
System.out.println(c.equals(a+b)); // true
System.out.println(g==(a+b)); // true == 封装类型 与 基本类型比较时,会自动拆箱
System.out.println(g.equals(a+b)); // false equals() 需要类型相同,值相同
System.out.println(g.equals(a+h)); // true 运算时 小容量类型自动响大容量类型转换
System.out.println(i1 == a); // false a 调用 Integer.valueOf(1) 自动装箱
System.out.println(i2 == i3); // true
}
引用
如有不当之处,敬请指正