Forums Register Login

an assignment operator ques

+Pie Number of slices to send: Send
Hi everybody,
byte b=0;
b=b+100; is an error but b+=100; is ok. can anyone tell me why. one reason that i can make out is that assignment operator casts the RHS to what the LHS is. Am i correct? but if that is true why is that?
+Pie Number of slices to send: Send
B = b + 100
What happens here is that byte is promoted to integer when doing the addition operation (this is done implicitly). The integer result is assigned back to a byte data type, which is wrong. You need to explicitly cast it back to byte, like this b = (byte) b + 100

B += 100
This code compiles and runs without error, because the compound operator involves an implicit cast to the type of the LHS. This code is equivalent to b = (byte) b + 100
+Pie Number of slices to send: Send
Note that the essence of what Vicken explained is correct. I'm just nitpicking a little bit.

For the official word on things, take a look at section 15.26.2 of the JLS on Compound Assignment Operators.

Originally posted by Vicken Karaoghlanian:
You need to explicitly cast it back to byte, like this b = (byte) b + 100



Almost. Don't forget to surround the entire value being cast with parentheses, in this example. Otherwise, the cast operator is only attempting to cast the value of b to a byte.

b = (byte)(b + 100);

B += 100
This code compiles and runs without error, because the compound operator involves an implicit cast to the type of the LHS. This code is equivalent to b = (byte) b + 100



Again, mostly correct. Just be sure to add some parentheses around b + 100.
Well THAT's new! Comfort me, reliable tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 608 times.
Similar Threads
Iterations - finding the same value for 2 variables
about using 'new'
Casting Problem
ternary operator doubt
Conversion
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:14:55.