本文介绍了类型不匹配:无法从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复合分配运算符:

对于二进制 + 运算符,则必须显式进行强制转换.进行第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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:11