基本数据类型与运算

245 阅读3分钟

基本数据类型与运算

类型存储取值范围默认值包装类
整数型
byte8最大存储数据量是 255,最小 -2^7,最大 2^7-1, [-128~127](byte) 0Byte
short16最大数据存储量是 65536,[-2^15,2^15-1], [-32768,32767],±3万(short) 0Short
int32最大数据存储容量是 2^31-1, [-2^31,2^31-1],±21亿,[ -2147483648, 2147483647]0Integer
long64最大数据存储容量是 2^64-1, [-2^63,2^63-1], ±922亿亿(±(922+16个零))0LLong
浮点型
float32数据范围在 3.4e-45~1.4e38,直接赋值时必须在数字后加上 f 或 F0.0fFloat
double64数据范围在 4.9e-324~1.8e308,赋值时可以加 d 或 D 也可以不加0.0dDouble
布尔型
boolean1true / flasefalseBoolean
字符型
char16存储 Unicode 码,用单引号赋值'\u0000' (null)Character

char类型为什么是2个字节?

java是使用unicode编码,一个字符16位,2字节

简述下字符,字符串,编码

自动装箱与拆箱
  • 从基础类型到引用类型称为装箱
  • 从引用类型到基础类型称为拆箱
有关Integer的自动装箱与拆箱问题

首先先看下Integer自动装拆箱机制

Integer i=100;
int j=i;
  • 当我们执行到*Integer i=100;这一行的时候,如果我们事先在valueOf()*方法处打了断点系统会停在此处,说明需要运行此方法。*valueOf()*方法如下:
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//IntegerCache数据结构
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;
    ....
}

他会判读输入的 i 是否在IntegerCache.low(-128)与IntegerCache.high(127)之间,如果在的话会直接返回cache这个数组里的值,如果不在这个范围内会返回一个new Integer(i),输入的是基础类型,返回类型是 Integer,所以叫做装箱。

  • 当我们执行到*int j=i;这一行的时候,如果我们事先在intValue()*方法处打了断点,系统会停在此处,说明需要运行此方法。*intValue()*方法如下
public int intValue() {
        return value;
    }

给的是integer类型,返回一个基础类型,所以叫做拆箱。

针对integer中的integerCache中的cache数组寻找其部分代码可知

static final Integer[] cache;
/******************************************************************/
for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)

cache是一个被final和static修饰的编译期常量,从注释可知范围在[-128, 127] ,根据前面的*valueOf()方法我们可以得知,但凡创建一个integer对象,只要值在[-128, 127] 之内,那么就返回cache数组里的值,超出了就在堆中(这个不太确定,1.8废除了new integer)*创建,所以会出现以下情况:

Integer i=100;
Integer j=100;
Integer k=200;
Integer l=200;
System.out.println(i==j); //true
System.out.println(k==l); //false

小补充:int最小值为何是-2147483648,而不是-2147483647

因为计算机是以补码的形式来存储数字的,最高位代表符号位,不管-0还是+0,补码都是0000 0000 0000 0000, 这样就多了一个位置,就规定用它来存储-(int_max-1)

其余的包装类跟Integer类中的IntegerCache这个静态内部类实现机制类似

(本文仅用于记录平时个人学习心得,如有误导恳请指教)