public static void main(String[] args) {
Character x = ' ';
while (x++ < 50) {
int p = x;
}
System.out.println(x instanceof Character);
}
Because it's a unary operation ++. x is unboxed into char and then widened into int before operation is performed. When I exit the loop, I get 'true'. I fail to understand how can int be boxed into Character back; java can allow boxing of int into Integer or boxing and widening int into Number, Object etc.
The answer lies in the Java Language Specification §15.14.2 Postfix Increment Operator ++
(Emphasis by me)
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.
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