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

1 类型转换

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

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

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

1.1 强制转换

可能造成精度损失

double d1 = 10.9
int i = (int)d1; // 10 精度损失

int i2 = 128;
byte b1 = (byte)i2; // -128 也算精度损失

(类型)变量名

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

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

1.2 自动转换

当容量(数的范围)小的数据类型的变量和容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。
当byte、char、short这三种类型的变量做运算时(包括同种类型之间),结果为int。

注意

  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
原文地址:https://www.cnblogs.com/zhangtu/p/14453728.html