Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notation for logic in Java

Absolutely basic Java question which I'm having a hard time finding on Google. What does the following mean:

(7 & 8) == 0?

Is that equivalent to writing:

7 == 0 || 8 == 0?

I wrote a quick main which tests this, and it seems to be the case. I just wanted to make sure I'm not missing anything.

like image 241
Sal Avatar asked Feb 08 '12 23:02

Sal


People also ask

How do you write logical OR in Java?

How to use the logical OR operator. We use the symbol || to denote the OR operator. This operator will only return false when both conditions are false. This means that if both conditions are true, we would get true returned, and if one of both conditions is true, we would also get a value of true returned to us.

What is logical expression in Java?

Logical expressions are also known as Boolean expressions . It will always evaluate to a value of either true or false. Therefore, they will be represented by the data type boolean. While they may seem similar to mathematical operators, the difference lies in how they are used with comparative or boolean operators.

What is && and || in Java?

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

Is && a logical operator in Java?

&& is a type of Logical Operator and is read as “AND AND” or “Logical AND“. This operator is used to perform “logical AND” operation, i.e. the function similar to AND gate in digital electronics.


1 Answers

Nope. & is bitwise and. It sets a bit if the corresponding bits are set in both inputs. Since in binary, 7 is 111 and 8 is 1000, they have no bits in common, so the result is 0.

There isn't really any shorthand syntax for the thing you suggest, not on a single line. There are a few workarounds -- test for membership in a Set or BitSet, use a switch statement -- but nothing that's both as efficient and as short as just 7 == 0 || 8 == 0.

like image 198
Louis Wasserman Avatar answered Sep 21 '22 15:09

Louis Wasserman