Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift operators - operands must be convertible to an integer primitive?

I'm preparing myself to a Java exam, and I'm reading "OCA Java SE 8 Programmer Study Guide (Exam 1Z0-808)". In operators section I found this sentence:

Shift Operators: A shift operator takes two operands whose type must be convertible to an integer primitive.

I felt odd to me so I tested it with long:

public class HelloWorld{

     public static void main(String []args){
         long test = 3147483647L;
         System.out.println(test << 1);

     }
}

and it worked, no compiler errors and result is correct. Does the book has a bug or am I misunderstanding the quote from the book?

like image 204
dragonfly Avatar asked Sep 28 '15 10:09

dragonfly


People also ask

What does shift () do in Java?

The shift operator is a java operator that is used to shift bit patterns right or left.

What are primitive operators?

A primitive operator is an operator that is implemented in the C++ or Java™ and that includes an operator model that describes the syntax and semantics of the operator. The result of expanding all composite operators is a stream graph where each vertex is a primitive operator instance.

What is shift operator in Python?

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.

What is >> and << in Java?

Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.


1 Answers

The shift operators >> and << are defined in JLS section 15.19. Quoting:

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.

When talking about "integer primitive", the book is really talking about "primitive integral type" (defined in 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
like image 108
Tunaki Avatar answered Oct 13 '22 22:10

Tunaki