-1

I've been told that there are differences between a+=b; and a=a+b; which can result in only one of those being legal depending on the type declerations.

Does anyone have an example of this?

mmgro27
  • 475
  • 1
  • 8
  • 18
  • [this](http://stackoverflow.com/questions/19957085/why-are-arithmetic-assignment-operators-more-efficient) might help you – Ankur Singhal Oct 10 '14 at 10:17
  • Thanks! That's what I was looking for e.g. declaring 'a' as a byte and 'b' as an int will result in a=a+b being illegal and a+=b being legal. – mmgro27 Oct 10 '14 at 10:25

3 Answers3

7

There is basically no difference, however there is a subtle difference.

The arithmetic assignment operators do an implicit cast. e.g.

byte a = 1;
int b = 2;

a += b; // compiles
a = a + b; // doesn't compile as a byte + int = int
a = (byte) (a + b); // compiles as this is the same as +=

For more weird examples.

int a = 5;
a += 1.5f;
// a == 6

char ch = '0'; // (char) 49
ch *= 1.1;     // ch = '4';

long l = Integer.MAX_VALUE;
l += 0.0f;   // i = (long ) ((long ) l + 0.0f)
// i == Integer.MAX_VALUE + 1L; WTF!?
// l is no longer Integer.MAX_VALUE due to rounding error.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

The JLS (section 15.26.2) says:

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.

The presence of the type-cast means that there are a couple of edge cases where a = a op b means something different to a op= b.

See Peter Lawrey's answer for one example. It is when a is a byte and b is an int and the "op" is +. The "gotcha" is a + b produces an int, which then can't be assigned to a ... without a typecast.

The same scenario applies with other types for a and b and for other arithmentic and bitwise operators.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1
int a = 10;
int b = 20;   
a=a+b; // 30

a+=b; // 30

System.out.println(a);

Both will give the same answer.

Naveen Kulkarni
  • 233
  • 2
  • 17