Short hand assignment operator, +=, True Meaning?
Asked Answered
M

2

5

I learnt that i+=2 is the short-hand of i=i+2. But now am doubting it. For the following code, the above knowledge holds no good:

byte b=0; b=b+2; //Error:Required byte, Found int

The above code is justifiable, as 2 is int type and the expression returns int value.

But, the following code runs fine:

byte b=0; b+=2; //b stores 2 after += operation

This is forcing me to doubt that the += short-hand operator is somewhat more than I know. Please enlighten me.

Meltage answered 3/5, 2013 at 15:3 Comment(2)
See: #7038512Mana
No use in answering when a good answer exists. Check this one out. This question is covered there.Niemi
P
10

When in doubt, you can always check the Java Language Specification. In this case, the relevant section is 15.26.2, Compound Assignment Operators.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So you were almost correct, except that a cast is added as well. In your case: b+=2; qualifies to b=(byte)(b+2);

Poison answered 3/5, 2013 at 15:6 Comment(5)
According to this wouldn't 2 still be considered an int? Filling in the placeholders, I read that as b = (byte)b + 2;Mana
So i+=2 qualifies to i=(type of i)(i+2). Thanks :)Curling
@KevinBowersox No, you have to read that as b = (byte)(b + 2);Harmonious
whoops I missed those extra parensMana
@Poison You must be really familiar with the spec to find this in two minutes.Mana
C
0

Coming from a C++ background, I can attempt to claim that the concept is similar. The operator += is defined as a method of the object to its left, passing in the object to its right as an argument. This makes it trivial for the writer of the language to throw in things like typecasting and compatibility fixes. The only thing is, as far as I know, Java doesn't allow the user to overload the operator functions

Cristiecristin answered 3/5, 2013 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.