Reputation: 17773
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?
Upvotes: 10
Views: 351
Reputation: 137114
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
Upvotes: 11
Reputation: 73558
They're using integer
not in the Java int
fashion, but rather as "integer type instead of floating point or other type". Java's long
is an integer too, it's just a 64-bit wide integer.
Upvotes: 4