java - 为什么 =+ 不会导致编译错误?

标签 java operators

遇到有人在他们的代码中错误地使用 =+ 而不是 += 并且它没有显示为编译错误。

这是因为

int a =+ 2;

相同
int a = 0 + 2;

?

最佳答案

没有编译错误,因为 + 是一个有效的(尽管相当无用)一元运算符,就像 - 一样:

int x = +1;
int y = -1;

Java 语言规范中的相关部分是Unary Plus Operator + (§15.15.3 ) .它指定调用一元 + 操作会导致 Unary Numeric Promotion (§5.6.1)的操作数。这意味着:

  • If the operand is of compile-time type Byte, Short, Character, or Integer, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of type int by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).

  • Otherwise, if the operand is of compile-time type Long, Float, or Double, it is subjected to unboxing conversion (§5.1.8).

  • Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

  • Otherwise, a unary numeric operand remains as is and is not converted.

In any case, value set conversion (§5.1.13) is then applied.

简而言之,这意味着

  1. 数字原始包装类型未装箱,并且;
  2. 小于 int 的整数类型加宽int

关于java - 为什么 =+ 不会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27371075/

相关文章:

python - 按位运算和使用

php - 解析错误: syntax error, unexpected '<<' (T_SL) in C:\xampp\htdocs\kensift\index.php on line 167 [duplicate]

c++ - C++ 中的运算符 <<<> 是什么?

java - 不指定类路径时,默认的类路径是什么?

java - 在哪里可以找到适用于 Windows 的 32 位服务器 jre

java - JSON Jackson - 使用自定义序列化程序序列化多态类时出现异常

java - 无法比较的类型(int 和 obj)(bug?)

swift ,两个问题。 1) weak var 2) @IBOutlet 的 bang 运算符

java - 如何将在 fragment 中创建的 ArrayList<String> 传递给主要 Activity

java - 这是合并排序的稳定实现吗