Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

an assignment operator ques  RSS feed

 
Amit Ghai
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!