Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
byte
-> short
-> char
-> int
-> long
-> float
-> double
double
-> float
-> long
-> int
-> char
-> short
-> byte
Widening casting is done automatically when passing a smaller size type to a larger size type:
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
}
}
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
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
}
}
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!