數(shù)據(jù)類型的轉換,分為自動轉換和強制轉換。自動轉換是程序在執(zhí)行過程中“悄然”進行的轉換,不需要用戶提前聲明,一般是從位數(shù)低的類型向位數(shù)高的類型轉換;強制類型轉換則必須在代碼中聲明,轉換順序不受限制。
自動數(shù)據(jù)類型轉換
自動轉換按從低到高的順序轉換。不同類型數(shù)據(jù)間的優(yōu)先關系如下:
低--------------------------------------------->高
byte,short,char-> int -> long -> float -> double
| 操作數(shù)1類型 | 操作數(shù)2類型 | 轉換后的類型 |
|---|---|---|
| byte、short、char | int | int |
| byte、short、char、int | long | long |
| byte、short、char、int、long | float | float |
| byte、short、char、int、long、float | double | double |
運算中,不同類型的數(shù)據(jù)先轉化為同一類型,然后進行運算,轉換規(guī)則如下:
| 操作數(shù)1類型 | 操作數(shù)2類型 | 轉換后的類型 |
|---|---|---|
| byte、short、char | int | int |
| byte、short、char、int | long | long |
| byte、short、char、int、long | float | float |
| byte、short、char、int、long、float | double | double |
強制數(shù)據(jù)類型轉換
強制轉換的格式是在需要轉型的數(shù)據(jù)前加上“( )”,然后在括號內(nèi)加入需要轉化的數(shù)據(jù)類型。有的數(shù)據(jù)經(jīng)過轉型運算后,精度會丟失,而有的會更加精確,下面的例子可以說明這個問題。
public class Demo {
public static void main(String[] args){
int x;
double y;
x = (int)34.56 + (int)11.2; // 丟失精度
y = (double)x + (double)10 + 1; // 提高精度
System.out.println("x=" + x);
System.out.println("y=" + y);
}
}
運行結果:
x=45
y=56.0
仔細分析上面程序段:由于在 34.56 前有一個 int 的強制類型轉化,所以 34.56 就變成了 34。同樣 11.2 就變成了 11 了,所以 x 的結果就是 45。在 x 前有一個 double 類型的強制轉換,所以 x 的值變?yōu)?45.0,而 10 的前面也被強制成 double 類型,所以也變成 10.0,所以最后 y 的值變?yōu)?56。