gpt4 book ai didi

Java boolean 值 |= 运算符

转载 作者:IT老高 更新时间:2023-10-28 21:18:42 26 4
gpt4 key购买 nike

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

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/

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