下面的变量(称为 b)是否可以称为表达式,如果它是唯一位于等号右侧的东西?
// This code fragment will not compile.
// c is a char, and b is a byte.
c = b;
我问这个问题的原因是因为表达式中类型提升的主题。我知道 Java 将所有字节提升为整数。这是此代码片段无法编译的唯一原因吗? (请注意,我了解强制转换;这不是本主题的重点。非常感谢。)
编辑: 非常感谢乔恩和彼得。使用第二个示例查看此主题:
byte b = 1;
short s = 2;
s = b; // OK
s = b*2; // Not OK (compilation error)
下面的情况是真的吗?
(第 3 行)Java 将 byte 转换为 short。 (第 4 行)Java 将表达式 b*2 转换为 int。
如果这是正确的,那么 =b;和=b*2;是 Java 以不同方式处理的“表达式”。所以, =b; “表达式”未转换为 int,而是扩展为 short。但是 =b*2; expression 被转换为 int,而不是 short,即使名为 s 的目标变量是 short。
编辑 2: 还有——
short s1, s2 = 2, s3 = 2;
s1 = s2*s3; // Not OK (compilation error)
即使所有三个变量都是短路,s2*s3; expression 被提升为 int,从而导致编译错误。
最佳答案
试试这个
byte b = -1;
short s = b; // is ok as a byte can be promoted to an short.
int i = b; // is ok as a byte can be promoted to an int.
float f = b; // is ok as a byte can be promoted to an float, long or double.
char c = b; // won't compile
但是
final byte b = 1;
char c = b; // compiles fine as the compiler can inline the value.
在这种情况下
short s = b*2; // Not OK (compilation error)
b * 2 是一个 int
,因为 2
是一个 int
值。如果 b
是最终的,你就可以这样做,因为编译可以内联该值。
关于带有 "expressions"的 Java 类型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19723658/