use*_*290 2 java promotions types
下面的变量(称为b)可以被称为表达式,如果它是唯一位于等号右边的东西吗?
// This code fragment will not compile.
// c is a char, and b is a byte.
c = b;
Run Code Online (Sandbox Code Playgroud)
我问这个问题的原因是因为表达式中的类型提升主题.我知道Java将所有字节提升为整数.这是该代码片段无法编译的唯一原因吗?(请注意,我知道演员阵容;这不是这个帖子的重点.非常感谢.)
编辑:非常 感谢Jon和Peter.使用第二个示例查看此主题:
byte b = 1;
short s = 2;
s = b; // OK
s = b*2; // Not OK (compilation error)
Run Code Online (Sandbox Code Playgroud)
以下是否真的发生了?
(第3行)Java将字节转换为short.(第4行)Java将表达式b*2转换为int.
如果这是正确的,那么它似乎= b; 和= b*2; 是Java处理不同的"表达式".所以,= b; "表达式"不会转换为int,而是扩展为short.但是= b*2; 表达式转换为int,而不是短,即使名为s的目标变量是短的.
编辑2: 还 -
short s1, s2 = 2, s3 = 2;
s1 = s2*s3; // Not OK (compilation error)
Run Code Online (Sandbox Code Playgroud)
即使所有三个变量都是短路,s2*s3; 表达式被提升为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
Run Code Online (Sandbox Code Playgroud)
但
final byte b = 1;
char c = b; // compiles fine as the compiler can inline the value.
Run Code Online (Sandbox Code Playgroud)
在这种情况下
short s = b*2; // Not OK (compilation error)
Run Code Online (Sandbox Code Playgroud)
的b*图2是int作为2为int值.如果b是最终的,你可以做到这一点,编译可以内联值.