Originally posted by Ajith Kallambella:
I still cant figure out why the following code works.
byte b = 10 ;
b = b++ ;
Since ++ does an implicit conversion to int,
how come the assignment works here? Try it
out with b = 127, and it still works!
I am very very
<pre>
Hi! Here goes,
First:
<code>
byte b = 10;
b = b++;
</code>
Your code is setting the var "b" to its "old" value
which is 10. You are incrementing b and then setting
it back to its old value.
Second:
I gather from your question that you want to know
about the narrowing and widening conversion rules.
I am assuming that you know about the
binary numeric
promotion and
narrowing primitive conversion <bold>
This is from JLS.
15.14.1 Prefix Increment Operator ++ [...]
At run time, if evaluation of the operand expression
completes abruptly, then the prefix 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) to the type of the variable before it is
stored. The value of the prefix increment expression is the
value of the variable after the new value is stored.
So
<code>
(1) byte b = 127;
(2) b++; // [ same as b = b + 1]
</code>
Apply numeric promotion. So now "b" and "1" are ints.
so now (before addition) the
int b is
00000000 00000000 00000000 01111111
after addition :
00000000 00000000 00000000 10000000
Now apply narrowing conversion (which means
pick up the lowest order 8 bits)
So you have a
byte b 10000000
The signed bit is set and the value is -128.
HTH
BoN.