JAVA基础--数据类型

基本数据类型

1 八个内置数据类型

类型 占内存 表示范围 实例默认值 对应包装类(java.lang包)
byte 1字节/8位 \([-2^{7},2^{7}-1]\) 0 Byte
short 2字节/16位 \([-2^{15},2^{15}-1]\) 0 Short
int 4字节/32位 有符号整数:\([-2^{31},2^{31}-1]\)
无符号整数:\([0,2^{32}-1]\)
0 Integer
long 8字节64位 \([-2^{63},2^{63}-1]\) 0L Long
float 4字节/32位 单精度浮点数 0F Float
double 8字节/64位 双精度浮点数(默认类型) 0D Double
char 2字节/16位 16位Unicode字符
最小值为:\u0000(0)
最大值为:\uffff(65535)
\u0000 Character
boolean 1位 true/false false Boolean

JAVA获取前七个类型的最大最小值以及大小(位)

// 通过类型包装类获取类型最大值、最小值、二进制位数
// 均以常量的形式存储在包装类中
// 最大值:MAX_VALUE
// 最小值:MIN_VALUE
// 二进制位数:SIZE
publi class PrimitiveTypeTest{
    public static void main(String[] args){
        System.out.println(包装类.MAX_VALUE); // 最大值
        System.out.println(包装类.MIN_VALUE); // 最小值
        System.out.println(包装类.SIZE);      // 二进制位数
    }
}

类型转换

自动数据类型转换

  • byte, short, char -> int -> long -> float -> double
public class TypeAutoChangeTest{
    public static void main(String[] args){
        byte b = 1;
        int i = b;
        System.out.println(i);
        char c = 'S';
        int i = c;
        System.out.println(i);
        short s = 1;
        int i = s;
        System.out.println(i);
        long l = i;
        System.out.println(l);
        float f = l;
        System.out.println(f);
        double d = f;
        System.out.println(d);
    }
}
  • byte,short,char进行计算时,会首先转化为int类型,最终结果也是int类型
  • byte -> short
public class ByteShortCharToInt{
    public static void main(String[] args){
        byte b = 1;
        short s = 1;
        char c = "A";
        s = b+s; // 报错:需要的类型是short, 给的类型是int
        System.out.println(s);
        c = c+s;  // 报错:需要的类型是char,给的类型是int
        System.out.println(c);
        s = b;  // byte -> short
        System.out.println(s);
    }
}

强制类型转换

public class CastType{
    public static void main(String[] args){
        int i = 123;
        byte b = (byte)i; // 前置括号进行强制类型转换
        int i = 128;
        byte b = (byte)i; // 会发生溢出,最终赋值为-127
    }
}

2 基本类型对应的缓存池

Java为每一个基本类型的包装类创建了一个缓存池用以存储预定义的对象(值)

  • Boolean:true\false

  • Byte: all values, [-128,127]

  • Short: [-128,127]

  • Integer: [-128,127]

  • Character: \u0000~\u007f

在使用这些基本类型的包装类时,如果没有通过new新建对象,并且赋的值在缓存池范围中,那么就会直接引用缓存池对象(同样的值内存地址一致)

Integer x = 123;
Integer y = 123;
System.out.println(x==y); // true
Integer a = Integer.valueOf(13);
Integer b = Integer.valueOf(13);
System.out.println(a==b); //true
Integer c = new Integer(13);
System.out.println(b==c); // false

如果在缓存池范围之外,会自动新建对象,内存地址不一致

修改缓存池范围(IntegerCache):-XX:AutoBoxCacheMax,在JVM运行参数上添加该参数并赋值

posted @ 2022-04-07 22:36  Moon_Bai  阅读(36)  评论(0)    收藏  举报