逻辑运算结果

result of logical operation

For the logical operators, the operands must be of the type boolean

假设如下代码:-

int p,q;

p=1;

q=1;

System.out.println("The result is : "+(p&q));

输出

结果是:1

我的问题是,在上面的代码中,两个变量都不是Boolean类型。那为什么这段代码没有产生错误呢?

还有

System.out.println(" This is an error : "+(!p));

为什么这个语句会产生错误?

虽然使用的符号看起来很相似,但这不是布尔运算,
这是按位运算,returns 是 int,而不是 boolean。另见:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

请注意,您使用的是 &(按位与)而不是 &&(逻辑与)。

p&q 是两个整数的按位与,而不是逻辑运算符。

!p 无效,因为整数上没有 ! 一元运算符。 ! 仅为布尔值定义。

& 是按位与运算符。

Binary AND Operator copies a bit to the result if it exists in both operands

比如你的情况。

p = 1(整数)= 0001(二进制) q = 1(整数)= 0001(二进制)

   0001

 & 0001
---------
   0001

导致 0001 = 1 in int.

另一方面,

&& 是逻辑运算符,需要布尔操作数。

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

进一步!也是逻辑运算符和必需的布尔操作数。

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

供参考,visit this site.