类型不匹配:无法从long转换为int [英] Type mismatch: cannot convert from long to int

查看:155
本文介绍了类型不匹配:无法从long转换为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 to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆