类型不匹配:无法从long转换为int [英] Type mismatch: cannot convert from long to int
问题描述
我有以下几行代码
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);
我认为3号线和4号线可以完成相同的任务,那为什么编译器在第4行类型不匹配:无法从long转换为int"上显示错误?
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"
请帮助.
推荐答案
这是因为复合赋值运算符会进行隐式转换.
That's because the compound assignment operator does implicit casting.
来自 JLS复合分配运算符:
格式为
E1 op = E2
的复合赋值表达式等效于E1 =(T)(((E1)op(E2))
,其中T
是E1
的类型,除了E1
仅被评估一次.
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
对于二进制 +
运算符,则必须显式进行强制转换.进行第4个作业:
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.
这篇关于类型不匹配:无法从long转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!