Java 型別轉換
Java 型別轉換
型別轉換是指將一個原始資料型別的值賦給另一種型別。
在 Java 中,有兩種型別的轉換:
- 擴大轉換(自動) - 將較小的型別轉換為較大的型別大小
byte
->short
->char
->int
->long
->float
->double
- 縮小轉換(手動) - 將較大的型別轉換為較小的型別大小
double
->float
->long
->int
->char
->short
->byte
擴大轉換
當將一個較小大小的型別傳遞給一個較大大小的型別時,擴大轉換會自動完成
示例
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
縮小轉換
縮小轉換必須透過將型別放在值前面的括號 ()
中來手動完成
示例
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
現實生活中的例子
這是一個關於型別轉換的現實生活中的例子,我們建立一個程式來計算使用者得分相對於遊戲中最高得分的百分比。
我們使用型別轉換來確保結果是一個浮點值,而不是一個整數
示例
// Set the maximum possible score in the game to 500
int maxScore = 500;
// The actual score of the user
int userScore = 423;
/* Calculate the percantage of the user's score in relation to the maximum available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0f;
System.out.println("User's percentage is " + percentage);