管道角色在Java方法调用中做了什么?
我已经看到了Java程序中方法调用中使用的管道字符。
例如:
public class Testing1 { public int print(int i1, int i2){ return i1 + i2; } public static void main(String[] args){ Testing1 t1 = new Testing1(); int t3 = t1.print(4, 3 | 2); System.out.println(t3); } }
当我运行这个时,我只得到7
。
有人可以解释管道在方法调用中的作用以及如何正确使用它吗?
管道在3 | 2
3 | 2
是按位包含OR运算符,在您的情况下返回3(二进制中11 | 10 == 11
)。
这是一个按位OR。
数字的按位表示如下:
| 2 ^ 2 | 2 ^ 1 | 2 ^ 0 | | 4 | 2 | 1 |
- 3的按位表示是:
| 2 ^ 2 | 2 ^ 1 | 2 ^ 0 | | 4 | 2 | 1 | | - | X | X | => 3
- 2的按位表示是:
| 2 ^ 2 | 2 ^ 1 | 2 ^ 0 | | 4 | 2 | 1 | | - | X | - | => 2
按位OR将返回3,因为使用OR时,至少必须“占用”一位。 由于第一位和第二位被占用(3 | 2)将返回3。
最后,加4 + 3 = 7。
|
运算符对操作数执行按位OR:
3 | 2 ---> 0011 (3 in binary) OR 0010 (2 in binary) --------- 0011 (3 in binary)
这是模式:
0 OR 0: 0 0 OR 1: 1 1 OR 0: 1 1 OR 1: 1
使用|
:
if(someCondition | anotherCondition) { /* this will execute as long as at least one condition is true */ }
请注意,这类似于if
语句中常用的短路 OR( ||
):
if(someCondition || anotherCondition) { /* this will also execute as long as at least one condition is true */ }
(除了||
没有强制要求在找到真实表达式后继续检查其他条件。)