java - 为什么 Java 中的扩充赋值运算符会给出不同的结果?

标签 java operators

<分区>

考虑以下代码:

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

编译器抛出以下错误:

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

如果我更改 main() 方法的第二行并使用 *= 速记运算符:

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

代码成功编译并运行并输出:

Result is: 2

为什么 *= 速记运算符的行为与完整表达式 num = num * 2.5 不同?

最佳答案

来自 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

它真的很新,所以我愿意接受建议。

关于java - 为什么 Java 中的扩充赋值运算符会给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862598/

相关文章:

java - 从 Liferay 门户获取文章

java - 字段中的列 ' ' 不明确

java - 在java web应用程序中哪里将arrayList类型变量定义为静态?

haskell - 在 Haskell 函数定义的参数符号之间使用冒号有什么作用?

javascript - JS 中的运算符问题

java - 嵌套关系实体中传递的空值 - Spring Boot

java - Hibernate:没有实体类的外键,只能通过id

C# 接口(interface)不能包含运算符

scala - 如何在 Scala 中定义赋值运算符?

linux - Bash 文件名前缀替换