我正在准备
Java考试,我正在阅读“OCA Java SE 8程序员学习指南(考试1Z0-808)”.在运算符部分我发现这句话:
Shift Operators: A shift operator takes two operands whose type must be
convertible to an integer primitive.
我对我感到奇怪,所以我测试了很长时间:
public class HelloWorld{ public static void main(String []args){ long test = 3147483647L; System.out.println(test << 1); } }
解决方法
移位运算符>>和<定义在
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.
当谈到“整数原始”时,这本书真的在谈论“原始积分类型”(定义在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