in java, char a=5 and using leftshift operator as println(a<<18) /* outcome: 262144 */ and it still giving further answers after 16 bit but it shouldnt because char in java is 16 bit. Why?
Asked
Active
Viewed 264 times
-2
-
2... I really didn't understand what you said. What is the problem? What is your question? – BackSlash Feb 25 '19 at 11:57
-
1`<<` will implicitly convert the `char` to an `int` – Lino Feb 25 '19 at 11:58
-
I get `1310720`. And from `a<<36` I get `80`. – Ole V.V. Feb 25 '19 at 11:59
1 Answers
2
Left shift is applied to int
or long
operands. When you apply it to a char
and an int
, the char
is promoted to an int
, and the result is an int
. Therefore 262144 is a valid result.
The shift operators are syntactically left-associative (they group left-to-right).
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.
The type of the shift expression is the promoted type of the left-hand operand.
-
-
2@Lino JLS says `Unary numeric promotion (§5.6.1) is performed on each operand separately.` – Eran Feb 25 '19 at 12:00
-
you're right, got confused with [*boxing*](https://stackoverflow.com/a/3995722/5515060) – Lino Feb 25 '19 at 12:02
-
Char as all other types are widened during conversion to int. It's good to say that int is the center of Java universe. – MS90 Feb 25 '19 at 12:03
-
1@MS90 - That's not really correct. Types are promoted to the closest bigger type. char is widened to int not because int is the center of java universe, but because it's the closest type which can handle a char (of course long could too, but it's too big and it would be unnecessary). – BackSlash Feb 25 '19 at 12:21
-
@BackSlash I agree to disagree that int is not the center of Java universe! All calculations/manipulations of bytes(!!!), shorts and chars are all widened to integer types during calculation. Considering that nearly almost everything in Java comes to subject mentioned above it is clear that int is the center of Java universe! – MS90 Feb 25 '19 at 15:00