1.知识点
Java表达式转型规则由低到高转换:
- 所有的byte,short,char型的值将被提升为int型;
- 如果有一个操作数是long型,计算结果是long型;
- 如果有一个操作数是float型,计算结果是float型;
- 如果有一个操作数是double型,计算结果是double型;
- 被fianl修饰的变量不会自动改变类型,当2个final类型的变量进行运算时,结果会根据等号左边变量(结果)的类型而转化。
2.测试code
public class Main {
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);在线笔试
//byte测试
byte b1=1,b2=2,b3,b6,b8;
final byte b4=4,b5=6,b7;
b3=(b1+b2); /*错误行,提示错误:Incompatible types: Required byte,Found int.*/
b6=b4+b5; /*错误行,提示错误:Incompatible types: Required byte,Found int.*/
b8=(b1+b4); /*错误行,提示错误:Incompatible types: Required byte,Found int.*/
b7=(b2+b5); /*错误行,提示错误:Incompatible types: Required byte,Found int.*/
System.out.println(b3+b6);
//short测试
short s1=1,s2=2,s3;
final short s4=5,s5=5,s6;
s3=s1+s2; /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s3=(s1+s2); /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s3=(short)(s1+s2);
s3=s1+s4; /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s3=(short)(s1+s4);
s3=s4+s5;
s6=s1+s2; /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s6=(s1+s2); /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s6=(short)(s1+s2);
s6=s1+s4; /*错误行,提示错误:Incompatible types: Required short,Found int.*/
s6=(short)(s1+s4);
//char测试
char c1=1,c2=2,c3;
final char c4=4,c5=5,c6;
c3=c1+c2; /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c3=(c1+c2); /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c3=(char)(c1+c2);
c3=c1+c4; /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c3=(c1+c4); /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c3=(char)(c1+c4);
c3=c4+c5;
c3=(c4+c5);
c6=c1+c2; /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c6=(c1+c2); /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c6=(char)(c1+c2);
c6=c1+c4; /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c6=(c1+c4); /*错误行,提示错误:Incompatible types: Required char,Found int.*/
c6=(char)(c1+c4);
c6=c4+c5;
//final类型测试
byte x1=b4+b5;
short x2=b4+b5;
int x3=b4+b5;
long x4=b4+b5;
float x5=b4+b5;
double x6=b4+b5;
char x7=b4+b5;
}
}