本文转载自http://blog.csdn.net/wang740209668/article/details/57416778
一般来说,在运算的时候,要求参与运算的数据的类型须一致,这就好比我们能用1+1进行运算,而不能用1+a进行运算,而在java中更为严格,同为数值的数字有byte short int long 四种不同的类型,它们在运算的时候也要求类型一致,如果不一致,就涉及到我们今天要说的类型转换。
默认转换:
- class TypeConvert
- {
- public static void main(String[] args){
- // 类型一致 直接运算
- int a = 1;
- int b = 2;
- System.out.println(a+b);
- // 类型不一致 默认转换 按道理讲 c+d=3 是没有超出byte 范围的
- // 但当我们用byte接收的时候,编译报错 可能损失精度。说明此时
- // e 不是byte类型,而运算的过程中byte c默认转换为 int c
- // 此时 结果 e 也是int类型了 ,我们需要用 int 接收
- byte c = 1;
- int d = 2;
- //byte e = c+d; 是int不是byte
- int e = c+d;
- System.out.println(e);
- // byte 和 byte 结果也是 int
- byte x = 1;
- byte y = 2;
- //byte z = x+y;
- int z = x+y;
- System.out.println(z);
- }
- }
默认转换顺序(从小到大,向上转型):
byte short char ->int->long->float->double
byte short char 运算时转换为int ,运算中有long类型则结果是long类型,有double类型,结果是double类型。
byte short char 相互之间不转换,它们运算时先转换为int类型。
/*
这一段为转载后插入
short s = 1;
s+=1;//不报错
//s = s+1;//报错 int不能复制给short
就是这个原因。+=不会提升数据类型 先+再赋值会
基本数据类型的字节大小如下:
boolean 8bit/1byte
byte 8bit/1byte
char 16bit/2byte
short 16bit/2byte
float 32bit/4byte
int 32bit/4byte
long 64bit/8byte
double 64bit/8byte
*/
强制转换(从大到小,向下转型):
格式 目标数据类型 变量 = (目标数据类型) 数据;
- class TypeConvert
- {
- public static void main(String[] args){
- byte a = 1;
- byte b = 2;
- // 强制类型转换
- byte c = (byte)(a+b);
- System.out.println(c);
- }
- }