java - 为什么这个赋值不需要显式转换?

标签 java casting operators

考虑这段代码:

byte b=1;
long l=1000;
b += l;

我希望最后一条语句需要显式转换,因为, b+=l 计算为 b = b+l 并且 (b+l) 部分给出一个整数。 如果没有显式转换,不能将整数分配给字节?

最佳答案

首先,b+l 给出了一个long,而不是一个int...

...但是复合赋值运算符有其他行为。根据 JLS section 15.26.2 :

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.

注意转换为 T

关于java - 为什么这个赋值不需要显式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603468/

相关文章:

c++ - std::string::npos == -1 总是为真吗?

c# - 使用 Type 对象将 Object 类型的对象转换为另一种类型

c# - 为什么字符串不比较引用?

java - JPQL 运算符返回 java.lang.IllegalStateException - 节点 : org. hibernate.hql.internal.ast.tree.MethodNode 没有数据类型

java - Java 中的 HTTP POST-GET 应用

java - 为什么我需要在 byte 和 short 上显式转换 char 原语?

java - 调用抛出 FileNotFoundException 的方法

php - VB 的 "AndAlso"在 PHP 中的等价物是什么?

java - Jersey 与 Spring 的融合

java - switch 语句无法识别