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);