Java -- 表达式类型的自动提升

1. 提升规则:

a. 所有byte型,short型和char型将被提升到int型。

b. 整个算数表达式的数据类型自动提升到与表达式中最高等级操作数同样的类型。

例1:

short val = 5; 

val = val -2 ;

编译时将报错 "Type mismatch: cannot convert from int to short",表达式中右边的val自动提升为int型,int --> short故报错。

例2:

byte b = 40;

char c = 'a';

int i = 23;

double d = 0.314;

double result = b + c + i*d ;

System.out.println(result);

表达式右边将提升为其中最高d的类型 double, 左边也是double, 所以正确。

例3:

System.out.println("hello" + ‘a’ + 7);        ------》 helloa7

System.out.println('a' + 7 + "hello");         -----》104hello

原文地址:https://www.cnblogs.com/xj626852095/p/3648086.html