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