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

不问归期 提交于 2021-01-27 17:46:29

问题


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.


回答1:


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.




回答2:


int a = 10;
a += 1.5;

is equivalent to:

int a = 10;
a = (int) (a + 1.5);

In general:

x += y; is equivalent to x = (type of x) (x + y);


See 15.26.2. Compound Assignment Operators




回答3:


Check this link

int a = 10;
a += 1.5;

will be treated as

int a=10;
a=(int)(a+1.5);

As you can found in this link expressions




回答4:


In case of

a += 1.5;

implicit auto boxing is done

where as here

a = a+1.5;

you are explicitly adding a int variable to a float/double variable

so to correct it

a = a+(int)1.5;

or

a = (int) (a+1.5);


来源:https://stackoverflow.com/questions/15107763/difference-between-variable-value-and-variable-variablevalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!