我知道一个数据类型会自动提升为上层数据类型 byte-short-int
class Temp {
void check(byte x) {
System.out.println(x + " is the byte type");
}
void check(short x) {
System.out.println(x + " is the short type");
}
void check(int x) {
System.out.println(x + " is the int type");
int y = x;
System.out.println(y + " is the int type");
}
void check(long x) {
System.out.println(x + " is the long type");
}
void check(float x) {
System.out.println(x + " is the float type");
}
void check(double x) {
System.out.println(x + " is the double type");
}
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result =" + result);
Temp t = new Temp();
t.check(f * b);
t.check(i / c);
t.check(d * s);
t.check(b + b);
t.check(b * b);
t.check(b * b * b);
t.check(b * b * b * b * b * b * b * b * b);
t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);
t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b);
}
}
输出:
238.14 + 515 - 126.3616
result =626.7784146484375
238.14 is the float type
515 is the int type
515 is the int type
126.3616 is the double type
84 is the int type
84 is the int type
1764 is the int type
1764 is the int type
74088 is the int type
74088 is the int type
-1889539584 is the int type
-1889539584 is the int type
-2147483648 is the int type
-2147483648 is the int type
0 is the int type
0 is the int type
我的问题是为什么 b*b 提升为 int 因为 42+42=84 并且字节范围是 -128 到 127。84 在范围内。此外,为什么
t.check(b * b * b * b * b * b * b * b * b * b * b * b * b * b * b * b
* b * b * b * b * b * b * b * b * b * b * b * b * b * b * b);
这条线得到 0 为什么不将它提升一倍。