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?
The shift operator is a java operator that is used to shift bit patterns right or left.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With