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.
The advantage is that the programmer does not need to write the variable again. It gives good readability and is more crisp. The shorthand is more efficient, especially in Java.
Java provides some special Compound Assignment Operators, also known as Shorthand Assignment Operators. It's called shorthand because it provides a short way to assign an expression to a variable. This operator can be used to connect Arithmetic operator with an Assignment operator.
The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.
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);
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