java程序中的类型转换可分为显式类型转换和隐式类型转换两种形式。
-
隐式类型转换
在表达式中,如果两边两个操作数的类型不一致,系统会自动转换为较高(即取值范围较大的)的类型。
数据类型按范围大小从小到大排列为:char,byte,short---short---int---long---float---double.
-
显式类型转换
显式类型转换需要人为的在表达式前面指明所需转换的类型,系统会按这一要求把某种类型强制的转换为指定的类型。
实例练习:
public class TypeConversion {
public static void main(String args[])
{
byte b=127;
char c='M';
short s=23561;
int i=3456;
long l=400000L;
float f=3.14159F;
double d=54.523;
//低类型向高类型自动转换
System.out.println("累加byte等于:"+b);
System.out.println("累加char等于:"+(b+c));
System.out.println("累加short等于:"+(b+c+s));
System.out.println("累加int等于:"+(b+c+s+i));
System.out.println("累加long等于:"+(b+c+s+i+l));
System.out.println("累加float等于:"+(b+c+s+i+l+f));
System.out.println("累加double等于:"+(b+c+s+i+l+f+d));
//高类型到低类型的强制转换
System.out.println("把long强制类型转换为int:"+(int)l);
//高类型到低类型转换会丢失数据
System.out.println("把long强制类型转换为short:"+(short)l);
//实数到整数转换会舍弃小数部分
System.out.println("把double强制转换为int:"+(int)d);
//整数到字符类型转换将获取对应编码的字符
System.out.println("把short强制类型转换为char:"+(char)s);
}
}