加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

JAVA中的速记运算符给出了两种不同的结果

发布时间:2020-12-15 04:49:06 所属栏目:Java 来源:网络整理
导读:我尝试了以下代码: class Converter{ public static void main(String args[]) { byte num = 1; num = num * 2.5; // line 1 System.out.println("Result is : "+num); }} 所以编译器抛出一个错误: error: incompatible types: possible lossy conversion
我尝试了以下代码:

class Converter{

    public static void main(String args[]) {
        byte num = 1;
        num = num * 2.5; // line 1
        System.out.println("Result is : "+num);
    }
}

所以编译器抛出一个错误:

error: incompatible types: possible lossy conversion from double to the byte at line 1

后来,我用简写操作符= *更改了第1行:

class Converter{

        public static void main(String args[]) {
            byte num = 1;
            num *= 2.5;
            System.out.println("Result is : "+num);
        }
    }

它已编译并成功运行输出:

Result is:2

我能否知道简写操作符在JAVA中的工作方式不同.为什么会这样呢?

解决方法

从JLS compound assigment operator文档中,您可以看到以下示例:

For example,the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

它只是默认自动转换结果.

PS:在这个other answer中,我试图解释你需要使用JLS进行如下操作的原因

short x = 3;
x = x + 1; //Won't compile

它是新的,所以我愿意在那里提出建议.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读