Java資料型別轉換(自動轉換和強制轉換)
阿新 • • 發佈:2019-01-06
自動資料型別轉換
自動轉換按從低到高的順序轉換。不同型別資料間的優先關係如下:
低———————————————>高
byte,short,char-> int -> long -> float -> double
運算中,不同型別的資料先轉化為同一型別,然後進行運算,轉換規則如下:
強制資料型別轉換
強制轉換的格式是在需要轉型的資料前加上“( )”,然後在括號內加入需要轉化的資料型別。有的資料經過轉型運算後,精度會丟失,而有的會更加精確。
下面的例子可以說明這個問題。
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