一、基本数据类型强制转换
自动类型转换的逆过程,将容量大的数据类型转换为容量小的数据类型。使用时要加上强制转换符( ),但可能造成精度降低或溢出。
package demo01;
public class Froce {
public static void main(String[] args) {
double a1 = 50.14;
int a2 = (int)a1;
char a3 = (char)a2;
System.out.println(a2);
System.out.println(a3);
}
}
二、注意事项
1、当进行数据的大小 从大到小,就需要使用到强制转换。
2、强转符号只针对于最近的操作数有效,往往会使用小括号提升优先级。
package demo01;
public class Froce {
public static void main(String[] args) {
int a1 = (int)(10*5.5+3.6);
System.out.println(a1);
}
}
3、char类型可以保存int的常量值,但不能保存int的变量值,需要强转。
4、byte和short, char类型在进行运算时,当做int类型处理。
三、练习
package demo01;
public class test01 {
public static void main(String[] args) {
short s = 12;
s = s - 9; //short不能接收int类型
byte b = 10;
b = b + 11; //同理
b = (byte)(b + 11);
char c = 'a';
int i = 16;
float d = .314f;
double result = c + i + d;
byte j = 16;
short k = 14;
short t = s + b; //类型不匹配
}
}