//介绍
//自动类型转换的逆过程,将容量大的数据类型转换为容量小的数据类型。
//使用时加上强制转换符(),但可能造成精度降低或者溢出格外要注意。
public class ForceConvert{
public static void main(String[] args){
int n1=(int)1.9;
System.out.println("n1="+n1);//精度损失
int n2=2000;
byte b1=(byte)n2;
System.out.println("b1="+b1);//数据溢出
//演示强制类型转换(细节)
//1.强转符号只针对于最近的操作数有效,往往会使用小括号提升优先级
//int x=(int)10*3.5+6*1.5;//编译错误:double
int x=(int)(10*3.5+6*1.5);
System.out.println(x);
//2.char类型可以保存int的常量,但不能保存int的变量,需要强制转换
char c1=100;//ok
int m=100;//ok
//char c2=m;//no int精度高于char会造成精度损失,需要强制转换
char c3=(char)m;//ok
System.out.println(c3);
//3.byte和short类型在进行运算时,当作int类型处理
byte b10=1;
byte b20=2;
short s1=1;
int s2=b20+s1;//ok,b2+s1=>int
//byte b4=b2+b3;//错误,b2+b3=>int
}
}
注:练习
public class ConvertDemo{
public static void main(String[] args){
short s=12;//ok
//s=s-9;//错误
//byte和short类型在进行运算时,当作int类型处理,int=>short错误
byte b=10;//ok
//b=b+11;//错误,byte和short类型在进行运算时,当作int类型处理,int=>short错误
b=(byte)(b+11);//ok
char c='a';//ok
int i=16;//ok
float d=.314f;//ok
double result=c+i+d;//ok
byte b1=16;//ok
short s1=14;//0k
//short t=s+b;//no byte和short类型在进行运算时,当作int类型处理
}
}