0
点赞
收藏
分享

微信扫一扫

03 数据类型转换

MaxWen 2022-01-20 阅读 68
java

数据类型转换

Java数据类型优先级 低——>高

byte,short,char ——> int ——> long ——>float ——> double

强制转换 高 ——>低

int i = 128;
byte b = (byte) i;  //内存溢出
       
System.out.println(i);
System.out.println(b);

自动转换 低 ——>高

int i1 = 128;
double d = i1;
System.out.println(i1);
System.out.println(d);

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

JDK8新特性,数字之间可以用下划线分割
int money = 10_0000_0000;
int year = 20;
int total = money*year;     //计算溢出
System.out.println((long)total);
  //默认是int,转换之前已经出现问题

long total2 = money*((long)year);
System.out.println(total2);

注意点:

  1. 不能对布尔值进行转换
  2. 不能把对象转换为不相干的类型
  3. 在把高容量转换为低容量的时候,强制转换
  4. 转换的时候可能存在内存溢出或者精度问题
举报

相关推荐

0 条评论