java – Shift操作符 – 操作数必须可以转换为整数原语?

前端之家收集整理的这篇文章主要介绍了java – Shift操作符 – 操作数必须可以转换为整数原语?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在准备 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
原文链接:https://www.f2er.com/java/122833.html

猜你在找的Java相关文章