Java 中的型別轉換是什麼?
資料類型 是一組預先定義的值,指定可以儲存在其中的值的類型以及可以對其執行的操作。為什麼需要型別轉換?
Java 有不同的原始資料類型,它們需要不同的記憶體空間。將一種資料類型的值指派給另一種資料類型時,這可能會導致相容性問題。如果資料類型已經相容,則編譯器會自動完成類型轉換。因此,類型轉換解決了程式中處理不同資料類型時的主要相容性問題。Java 類型轉換的型別
Java 中有兩種類型的型別轉換。- 加寬型別轉換- 也稱為隱式或自動型別轉換
- 縮小型別轉換— 也稱為顯式或手動型別轉換
加寬型鑄件
顧名思義,拓寬型別轉換是指將較小的資料型別拓寬為較大的資料型別。當我們想要將小類型轉換為大類型時,我們會執行這種類型轉換。資料類型必須相互相容。沒有從數字到 char 或 boolean 類型的隱式轉換。在 Java 中,char 和 boolean 類型是不相容的。
位元組 -> 短 -> 字元 -> int -> 長 -> 浮點 -> 雙精度
這種類型的轉換由編譯器自動完成,不會遺失任何資訊。它不需要程式設計師的任何外部觸發。
例子
//Automatic type conversion
public class WideningExample {
public static void main(String[] args) {
int i = 100;
System.out.println("int value: " + i);
// int to long type
long l = i;
System.out.println("int to long value: " + l);
// long to float type
float f = l;
System.out.println("int to float value: " + f);
byte b = 1;
System.out.println("byte value: " + b);
// byte to int type
i = b;
System.out.println("byte to int value: " + i);
char c = 'a';
System.out.println("char value: " + c);
// char to int type
i = c;
// prints the ASCII value of the given character
// ASCII value of 'a' = 97
System.out.println("char to int value: " + i);
}
}
輸出
int 值:100 int 轉 long 值:100 int 轉 float 值:100.0 byte 值:1 byte 轉 int 值:1 char 值:a char 轉 int 值:97
解釋
在上面的程式碼中,我們展示了由編譯器自動完成的加寬型別轉換。首先,我們為int、byte和char賦值。然後,我們將 int 值指派給long和float,它們都大於int。我們也將byte和char值指派給int。byte和char都是比int小的資料型,因此,這些轉換是隱式的 。縮小型鑄造
縮小型別轉換,顧名思義,是指將較大的資料型別縮小為較小的資料型別。當我們想要將大類型轉換為小類型時,我們會執行這種類型轉換。
雙精確度 -> 浮點 -> 長整型 -> int -> 字元 -> 短整數 -> 位元組
對於這種類型的轉換,我們透過指定我們自己的轉換來覆寫 Java 的預設轉換。為了實現這一點,我們將需要類型轉換的變數或值寫在括號「()」中,前面加上目標資料類型。然而,這種類型的鑄造可能會導致精度損失。
例子
//Manual Type Conversion
public class NarrowingExample {
public static void main(String[] arg) {
// double data type
double d = 97.04;
// Print statements
System.out.println("double value: " + d);
// Narrowing type casting from double to long
// implicitly writing the target data type in () followed by initial data type
long l = (long) d;
// fractional part lost - loss of precision
System.out.println("long value: " + l);
// Narrowing type casting from double to int
// implicitly writing the target data type in () followed by initial data type
int i = (int) l;
// fractional part lost - loss of precision
System.out.println("int value: " + i);
// Narrowing type casting from double to int
// implicitly writing the target data type in () followed by initial data type
char c = (char) i;
// displaying character corresponding to the ASCII value of 100
System.out.println("char value: " + c);
}
}
輸出
double 值:97.04 long 值:97 int 值:97 char 值:a
GO TO FULL VERSION