Reputation: 335
The JLS states that numeric promotion is applied to the operands of an arithmetic operator.
Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of: an identity conversion (§5.1.1) a widening primitive conversion (§5.1.2) an unboxing conversion (§5.1.8)
However, in my experience I found out that numeric promotion is also applied to the operands of other operators like bitwise operators. I found out this which states that
These conversions can occur when using the multiplicative operators (%, *, /), additive operators (+, -), comparison operators (<, >, <=, >=), equality operators (==, !=), and the integer bitwise operators (&, |, ^).
So am I missing something?
Edit: What about the other operators not listed like &&, ||, >>, <<, >>>, etc.?
Edit 2: As pointed out by @Turing85 and @Stephen C, this question is only valid for JLS 5 to 11 and has been resolved now.
Upvotes: 2
Views: 163
Reputation: 718788
The text you found appears in JLS section 5.6. It is worth noting the following:
If you read on to sections 5.6.1 and 5.6.2, you will find the operators that unary and binary numeric promotions apply to.
Note that the above is true for JLS editions 5 and 11. By JLS 14 they have folded sections 5.6.1 and 5.6.2 into section 5.6. The wording has changed (removing the text that you thought was contradictory). The relevant operators are all (still) listed.
(This is an editorial tidy-up, not a change in the actual language semantics.)
Upvotes: 1
Reputation: 111239
Binary numeric promotion (JLS 5.6.2) applies to operands of "certain binary operators" which includes the bitwise operators &, ^, and |. Quote:
Binary numeric promotion is performed on the operands of certain operators:
- The multiplicative operators *, /, and % (§15.17)
- The addition and subtraction operators for numeric types + and - (§15.18.2)
- The numerical comparison operators <, <=, >, and >= (§15.20.1)
- The numerical equality operators == and != (§15.21.1)
- The integer bitwise operators &, ^, and | (§15.22.1)
- In certain cases, the conditional operator ? : (§15.25)
As for && and ||, these are operators on booleans and there is numeric promotion.
Bit shift operators >>
, <<
, >>>
follow a different rule: unary numeric promotion is applied to the operands separately, and the type of the expression is determined solely by the left hand side operand. This means the following code is valid:
int i =1;
long l = 2;
int j = i << l;
Upvotes: 1