Are a += 10
and a = a + 10
both the same, or is there some difference between them? I got this question while studying assignments in Java.
+ is an arithmetic operator while += is an assignment operator.. When += is used, the value on the RHS will be added to the variable on the LHS and the resultant value will be assigned as the new value of the LHS..
=+ does nothing; it's the same as = here. You have just written sum1 = two . sum2 += one on the other hand is essentially the same as sum2 = sum2 + one .
++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand. a++ returns the value of a before incrementing.
+=, for adding left operand with right operand and then assigning it to the variable on the left. -=, for subtracting right operand from left operand and then assigning it to the variable on the left. *=, for multiplying left operand with right operand and then assigning it to the variable on the left.
As you've now mentioned casting... there is a difference in this case:
byte a = 5; a += 10; // Valid a = a + 10; // Invalid, as the expression "a + 10" is of type int
From the Java Language Specification section 15.26.2:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
Interestingly, the example they give in the spec:
short x = 3; x += 4.6;
is valid in Java, but not in C#... basically in C# the compiler performs special-casing of += and -= to ensure that the expression is either of the target type or is a literal within the target type's range.
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