測試的代碼: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