a += b
is short-hand for a = a + b
(though note that the expression a
will only be evaluated once.)
a =+ b
is a = (+b)
, i.e. assigning the unary +
of b
to a
.
Examples:
int a = 15;
int b = -5;
a += b; // a is now 10
a =+ b; // a is now -5
A common syntax is:
+=
This is the add and assignment operator, which adds right-hand expression to the left-hand variable then assigns the result to left-hand variable. For example:
int i = 1;
int j = 2;
i += j;
// Output: 3
System.out.println( i )
A far less common syntax is:
=+
Usually this is written as two different operators, separated by a space:
= +
Without the space, it looks as follows:
int i = 1;
int j = 2;
i =+ j;
// Output: 2
System.out.println(i);
An idiomatic way to write this is to shift the unary operator to the right-hand side:
int i = 1;
int j = 2;
i = +j;
// Output: 2
System.out.println(i);
Now it's easy to see that i
is being assigned to the positive value of j
. However, +
is superfluous, so it's often dropped, resulting in i = j
, effectively the equivalent of i = +1 * j
. In contrast is the negative unary operator:
int i = 1;
int j = 2;
i = -j;
// Output: -2
System.out.println(i);
Here, the -
would be necessary because it inverts the signedness of j
, effectively the equivalent of i = -1 * j
.
See the operators tutorial for more details.
Best Answer
The "common knowledge" of programming is that
x += y
is an equivalent shorthand notation ofx = x + y
. As long asx
andy
are of the same type (for example, both areint
s), you may consider the two statements equivalent.However, in Java,
x += y
is not identical tox = x + y
in general.If
x
andy
are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's havex == 0
(int) andy == 1.1
(double):+=
performs an implicit cast, whereas for+
you need to explicitly cast the second operand, otherwise you'd get a compiler error.Quote from Joshua Bloch's Java Puzzlers: