gpt4 book ai didi

java - 为什么 byte += 1 编译但 byte = byte + 1 不编译?

转载 作者:IT老高 更新时间:2023-10-28 20:51:48 26 4
gpt4 key购买 nike

如果我有一个字节变量:byte b = 0;

为什么以下工作:

   b++;
b += 1; // compiles

...但这不是吗?

   b = b + 1; // compile error

编译器是否首先理解为byte,其次理解为int

[编辑]

我知道类型转换,但我想提请您注意 b++, b += 1 和 b = b + 1

我认为它们是相等的,为什么编译器会区分它们?有什么区别

  b += 1 and b = b + 1 ?

最佳答案

因为 b += 1 等价于 b = (byte)(b + 1),而 b + 1 的类型被提升为 int ( JLS §5.6.2 Binary Numeric Promotion ),因此如果没有显式转换,它的结果不能分配给 byte

来自 JLS, §15.26.2 Compound Assignment Operators :

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.

关于java - 为什么 byte += 1 编译但 byte = byte + 1 不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4969339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com