Java(6):类型转换以及计算溢出问题

时间:2021-02-27 13:11:10   收藏:0   阅读:0

1 类型转换

? 由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换。运算中,不同类型的数据先转换为同一类型,然后进行运算。

低 -------------------------------------------------------------- 高

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

1.1 强制转换

由高到低

(类型)变量名

// 强制转换
int num1 = 128;
byte b1 = (byte) num1; // 由高到低

System.out.println(num1); // 128
System.out.println(b1); // -128 内存溢出 因为byte类型的大小范围为-128~127

1.2 自动转换

由低到高

注意

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

补充

JDK7新特性,数字之间可以用下划线分割,便于书写。

计算时也要注意内存溢出问题。

// 内存溢出,及JDK7新特性
int money = 10_0000_0000;
int years = 20;
int total = money * years;
System.out.println(total); // 内存溢出 -1474836480

long total2 = money * years;
System.out.println(total2); // -1474836480 默认是int 转换之前已经存在问题

long total3 = money * (long)years;
System.out.println(total3); // 20000000000
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!