移位运算符 - 操作数必须可转换为整数基元?
Shift operators - operands must be convertible to an integer primitive?
我正在准备 Java 考试,我正在阅读 "OCA Java SE 8 Programmer Study Guide (Exam 1Z0-808)"。在运算符部分我发现了这句话:
Shift Operators: A shift operator takes two operands whose type must be
convertible to an integer primitive.
我觉得很奇怪,所以我用 long 测试了它:
public class HelloWorld{
public static void main(String []args){
long test = 3147483647L;
System.out.println(test << 1);
}
}
它成功了,没有编译器错误,结果是正确的。这本书有错误还是我误解了书中的引述?
他们使用 integer
不是 Java int
的方式,而是 "integer type instead of floating point or other type"。 Java的long
也是一个整数,只是一个64位宽的整数。
移位运算符 >>
和 <<
在 JLS section 15.19 中定义。引用:
Unary numeric promotion (§5.6.1) is performed on each operand separately. (Binary numeric promotion (§5.6.2) is not performed on the operands.)
It is a compile-time error if the type of each of the operands of a shift operator, after unary numeric promotion, is not a primitive integral type.
书上说的"integer primitive"其实是在说"primitive integral type"(定义在JLS section 4.2.1):
The values of the integral types are integers in the following ranges:
- For byte, from -128 to 127, inclusive
- For short, from -32768 to 32767, inclusive
- For int, from -2147483648 to 2147483647, inclusive
- For long, from -9223372036854775808 to 9223372036854775807, inclusive
- For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
我正在准备 Java 考试,我正在阅读 "OCA Java SE 8 Programmer Study Guide (Exam 1Z0-808)"。在运算符部分我发现了这句话:
Shift Operators: A shift operator takes two operands whose type must be convertible to an integer primitive.
我觉得很奇怪,所以我用 long 测试了它:
public class HelloWorld{
public static void main(String []args){
long test = 3147483647L;
System.out.println(test << 1);
}
}
它成功了,没有编译器错误,结果是正确的。这本书有错误还是我误解了书中的引述?
他们使用 integer
不是 Java int
的方式,而是 "integer type instead of floating point or other type"。 Java的long
也是一个整数,只是一个64位宽的整数。
移位运算符 >>
和 <<
在 JLS section 15.19 中定义。引用:
Unary numeric promotion (§5.6.1) is performed on each operand separately. (Binary numeric promotion (§5.6.2) is not performed on the operands.)
It is a compile-time error if the type of each of the operands of a shift operator, after unary numeric promotion, is not a primitive integral type.
书上说的"integer primitive"其实是在说"primitive integral type"(定义在JLS section 4.2.1):
The values of the integral types are integers in the following ranges:
- For byte, from -128 to 127, inclusive
- For short, from -32768 to 32767, inclusive
- For int, from -2147483648 to 2147483647, inclusive
- For long, from -9223372036854775808 to 9223372036854775807, inclusive
- For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535