测试的代码:java
public class CastTests { public static void main(String[] args) { byte b = 1; short s = 1; int i = 1; float f = 1f; //自动转换。精度低的类型能够自动转为精度高的类型。 //自动转换方向:byte-->short-->int-->long-->float-->double s = b;//byte-->short f = i;//int-->float //须要强转。精度低的转为精度高的类型会丢失精度。 b = (byte) s;//short-->byte s = (short) i;//int-->short //自动转换。"+="操做会自动执行强制转换。 b += s;//至关于"b = (byte)b + s"。 b -= 1;//至关于"b = (byte)b - 1"。 s *= f;//至关于"s = (short)b * f"。 //通过算数运算符操做,右边的类型只能是int,long,float,double。 s = (short) (s + b);//(s + b)类型为int b = (byte) (b / b);//(b / b)类型为int i = (int) (i * f);//(i * f)类型为float f = i + f;//float-->float f = i * b;//int-->float i = s / b;//int-->int } }
注意几点:测试
一、自动类型转换是低精度往高精度方向,反之都须要强制转换,会损失精度。code
二、"+=, -=, *=, /="四个操做会执行强制类型转换,有时会丢失精度。ast
三、算数运算符操做以后的数据精度至少是int。也就是说,好比byte与byte类型相加减,结果类型是int或者更高精度(long,float,double)。class