Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between variable += value and variable = variable+value;

Tags:

java

operators

For example:

int a = 10;
a += 1.5;

This runs perfectly, but

a = a+1.5;

this assignment says Type mismatch: cannot convert from double to int. So my question is: what is the difference between += operator and = operator. Why the first assignment didn't says nothing, but second will. Please explain to me. Just I want to know whether I can use the first assignment to all place or not.

like image 320
Gunaseelan Avatar asked Feb 13 '26 12:02

Gunaseelan


1 Answers

From the Java Language Specification section 15.26.2:

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 the most important difference (in terms of why the second version doesn't compile) is the implicit cast back to the type of the original variable.

like image 180
Jon Skeet Avatar answered Feb 15 '26 01:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!