kevin gomes
kevin gomes

Reputation: 1815

result of logical operation

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

Suppose the following code:-

int p,q;

p=1;

q=1;

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

output

The result is : 1

My question is that in the above code, neither of the two variables is of the type Boolean. Then why this code is not producing error?

Also

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

Why this statement is producing an error?

Upvotes: 1

Views: 189

Answers (3)

codingenious
codingenious

Reputation: 8653

& is bit-wise AND operator.

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

For instance in your case.

p = 1 (int) = 0001 (binary) q = 1 (int) = 0001 (binary)

   0001

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

resulting to 0001 = 1 in int.

&& on the other hand is logical operator and requires boolean operands.

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

Further ! is also logical operator and required boolean operands.

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.

For reference, visit this site.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39477

Though the symbol used for it looks similar, this is not a boolean operation,
it's a bitwise operation and returns an int, not a boolean. See also:

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

Note that you used & (bitwise AND) and not && (logical AND).

Upvotes: 4

Eran
Eran

Reputation: 393936

p&q is bit-wise AND of two integers, not a logical operator.

!p is invalid since there is no ! unary operator on integers. ! is only defined for booleans.

Upvotes: 2

Related Questions