011_JAVA基础语法_类型转换

一、数据类型容量高低

从低到高

byte,short,char→int→long→float→double

二、类型转换

  1. 强制类型转换(数据类型由高容量→低容量)

    • 格式:(类型)变量名

  2. 自动类型转换(数据类型由低容量→高容量)

三、注意点

  1. 不能对布尔值进行类型转换;

  2. 不能把对象类型转换为不相干的类型;

  3. 在把高容量转换到低容量时,需要强制转换;低容量准换到高容量时,可自动完成,不需人为干预;

  4. 转换时要注意内存溢出、精度等问题。

//内存溢出问题
System.out.println((byte)128); //-128
//精度问题
System.out.println((int)23.7); //23

四、内存溢出实例

在操作比较大是数时注意溢出问题

//**JDK7新特性,数字之间可以使用下划线分割**
int money = 10_0000_0000;
int years = 20;
int total = money * years;      //-1474836480 计算时就已经溢出
long total2 = money * years;    //-1474836480   默认是int,转换之前就已经溢出?
System.out.println(total);
System.out.println(total2);

//先把一个数准换为long
long total3 = money * ((long)years);
System.out.println(total3);     //20000000000



posted @ 2022-03-13 14:54  小何呀  阅读(45)  评论(0)    收藏  举报