Java boolean 值 |= 运算符

标签 java operators specifications boolean-expression compound-assignment

最近我看到一个使用这个的代码:

boolean val = something();
val |= somethingElse();

有趣的部分是在 boolean 原始类型上创建的 |=(类似二进制)运算符。

令我惊讶的是, boolean 值存在 |=,就好像它是整数类型一样,并在 Java 规范中搜索该运算符,但找不到。

如果左值已经为真,我会很好奇是否计算右操作数。

有人可以指出我的 Java 规范吗?

最佳答案

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

15.22.2. Boolean Logical Operators &, ^, and |

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For |, the result value is false if both operand values are false; otherwise, the result is true.

这意味着

val |= somethingElse();

严格等价于

val = val | somethingElse();

(假设 somethingElse() 返回 booleanBoolean)。

I'd be curious if right operand is evaluated if left value already is true.

是的,它会被评估,因为 | 不会短路:

15.7.2. Evaluate Operands before Operation

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

15.24. Conditional-Or Operator ||

Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

关于Java boolean 值 |= 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15411219/

相关文章:

spring - 使用 Mockk 重载解决歧义的 kotlin 单元测试

java - 为什么 toString 方法被覆盖后不起作用?

C++:关于空字符

haskell - 我对幺半群的理解有效吗?

Python(或通用编程)。为什么使用 <> 而不是 != 并且有风险吗?

ruby-on-rails - Rails 3.1 中的规范失败 - NoMethodError : private method 'rand' called for Array

python - 为什么使用 python F 字符串插值用引号引起来?

java - 使用 jdbc 时尝试连接到远程 pg db 时出现奇怪的错误

java - 我应该使用 Thread.sleep 对其他程序友好吗?

java - string.replaceAll 问题