Type mismatch: cannot convert from long to int

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I had the following lines of code

long longnum = 555L; int intnum = 5; intnum+=longnum; intnum= intnum+longnum; //Type mismatch: cannot convert from long to int System.out.println("value of intnum is: "+intnum);

I think line-3 and line-4 do same task, then why compiler showing error on line-4 "Type mismatch: cannot convert from long to int"

please help.

回答1:

That's because the compound assignment operator does implicit casting.

From JLS Compound Assignment Operator:

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.

While in case of binary + operator, you have to do casting explicitly. Make your 4th assignment:

intnum = (int)(intnum+longnum);

and it would work. This is what your compound assignment expression is evaluated to.



回答2:

I think line-3 and line-4 do same task, then why compiler showing error on line-4 "Type mismatch: cannot convert from long to int"

Because they don't do the same thing. Compound assignment operators have an implicit cast in them.

From section 15.26.2 of the JLS:

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 your third line is more like:

intnum = (int) (intnum + longnum); 

The cast is required because in the expression intnum + longnum, binary numeric promotion is applied before addition is performed in long arithemtic, with a result of long. There's no implicit conversion from long to int, hence the cast.



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