- 基本数据类型转换
boolean类型不可以转换为其他的数据类型
整形,字符型,浮点型的数据在混合运算中相互转换,转换时遵循以下原则:
容量小的类型自动转换为容量大的数据类型;数据类型按容量大小排序为:
byte,short,char->int->long->float->double
byte,short,char之间不会互相转换,他们三者在计算时首先会转换为int类型
容量大的数据类型转换为容量小的数据类型时,要加上强制转换符.但可能造成精度降低或溢出;使用时要格外注意
有多种类型的数据混合运算时,系统首先自动的将所有数据转换成容量最大的那一种数据类型,然后再进行计算
实数常量默认为double
整数常量默认为int
- publicclassTestConvert{
- publicstaticvoidmain(Stringarg[]){
- inti1=123;
- inti2=456;
- doubled1=(i1+i2)*1.2;//系统将转换为double型运算
- floatf1=(float)((i1+i2)*1.2);//需要加强制转换符
- byteb1=67;
- byteb2=89;
- byteb3=(byte)(b1+b2);//系统将转换为int型运算,需
- //要强制转换符
- System.out.println(b3);
- doubled2=1e200;
- floatf2=(float)d2;//会产生溢出
- System.out.println(f2);
- floatf3=1.23f;//必须加f
- longl1=123;
- longl2=30000000000L;//必须加l
- floatf=l1+l2+f3;//系统将转换为float型计算
- longl=(long)f;//强制转换会舍去小数部分(不是四舍五入)
- }
- }
-
- publicclassTest{
- publicstaticvoidmain(Stringargs[])
- {
- inti=1,j;
- floatf1=0.1;//出错0.1是double
- floatf2=123;//
- longl1=12345678;
- longl2=8888888888;//有问题,超出
- doubled1=2e20;//没问题
- doubled2=124;//
- byteb1=1;
- byteb2=2;
- byteb3=129;//有问题
- j=j+10;//j没值
- i=i/10;//没问题,i=0
- i=i*0.1;//有问题0.1是double
- charc1='a';
- charc2=125;
- byteb=b1-b2;//有问题b1,b2先转换为int
- charc=c1+c2-1;//有问题
- floatf3=f1+f2;
- floatf4=f1+f2*0.1;//有问题0.1是double
- doubled=d1*i+j;
- floatf=(float)(d1*5+d2);
- }
- }