Avatar
11977 reputation
Posted on:15 Sep '16 - 10:37
65

Java's +=, -=, *=, /= compound assignment operators

Until today I thought that for example:

i += j;
is just a shortcut for:
i = i + j;
But what if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine. Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)

Answers

125
This answer is accepted

A good example of this casting is using *= or /=

 byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
 
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

Avatar
7979 reputation
Posted on:16 Sep '16 - 07:37

Please login in order to answer a question