1 基本数据类型转换
(1)小容量类型和大容量类型进行运算时,小容量类型会自动转换为大容量类型。
数据类型按容量进行排序:byte,short,char->int->long->float->double
class Test1 {
public static void main(String[] args) {
int i = 123;
double d = i * 3.14;
//int和double进行运算
//自动转换为double类型
}
}
(2)如果要把大容量类型转换为小容量类型时,需要进行强制转换的声明。但是精度可能会有损失。
class Test2 {
public static void main(String[] args) {
double d = 1e200;
float f = (float)d2;
System.out.println(f);
//输出结果为Infinity
//结果上溢了
byte b1 = 69;
byte b2 = 78;
byte b3 = (byte)(b1 + b2);
System.out.println(b3);
//输出结果为-9
//byte最多表示127
//与上者相比,这是可以输出的
//计算机内存直接把int后面截断
//变成byte
//但是浮点数在内存中并不能这么截断
//所以f的结果会无法表达
}
}
class Test3 {
public static void main(String[] args) {
char c1 = 'a';
char c2 = 125;
//char c = c1 + c2 - 1;
//会出现问题int转换成char
//应该显式声明强制转换
char c = (char)(c1 + c2 - 1);
float f1 = 0.1f;
float f2 = 123;
float f3 = f1 + f2;
//float f4 = f1 + f2 * 0.1;
//会出现问题,0.1默认是double
//所以得出来的结果会变为double
//应该显式声明强制转换为float
float f4 = (float)(f1 + f2 * 0.1);
}
}
(3)boolean类型不能和其他类型相互转换
附:例程
public class TestConvert {
public static void main(String[] args) {
int i = 1, j = 0;
// float f1 = 0.1;
// 0.1默认为double,大转小需显式转换
float f1 = 0.1f;
//123是int,小转大是自动转换
//f2不用转换
float f2 = 123;
// long l1 = 12345678, l2 = 8888888888;
// l2超过int表示范围应该在后面加L
long l1 = 12345678, l2 = 8888888888L;
double d1 = 2e20, d2 = 124;
//byte b1 = 1, b2 = 2, b3 = 129;
//byte最多表示127
byte b1 = 1, b2 =2, b3 = 127;
j = j + 10;
i = i / 10;
//i = i * 0.1;
//double转int,大转小应声明
i = (int)(i * 0.1);
char c1 = 'a', c2 = 125;
//byte b = b1 - b2;
//int转byte,大转小应声明
byte b = (byte)(b1 - b2);
//char c = c1 + c2 - 1;
//int转char,大转小应声明
char c = (char)(c1 + c2 - 1);
float f3 = f1 + f2;
//float f4 = f1 + f2 * 0.1;
//double转float,大转小应声明
float f4 = (float)(f1 + f2 * 0.1);
double d = d1 * i + j;
float f = (float)(d1 * 5 + d2);
}
}