Simple Boolean Logic

188 Views Asked by At

I'm trying to determine the conditions under which the following expression, where a and b are properly declared boolean variables, evaluates to false:

(a && (b || !a)) == a && b

To me, it seems that this expression will always evaluate to true. If either a or b is false, both sides of the equality operator will evaluate to false. If a and b are both true, then both sides will evaluate to true. That's all the options, and it's the correct answer for my online homework. However, when I run this in IntelliJ CE with the Java 11 JVM, it seems like it prints false whenever b is false: when a and b are both false, IntelliJ outputs false

I get the same output when b is false and a is true. Can someone explain where the fault in my logic is? Thank you very much.

3

There are 3 best solutions below

0
On BEST ANSWER

I think it is giving == operation priority over &&

Try this -

(a && (b || !a)) == (a && b)
0
On

You code should be:

boolean c = (a && (b || !a)) == (a && b);

otherwise it is evaluated as:

boolean c = ((a && (b || !a)) == a) && b;
0
On

Boolean operations have equivalent mathematical operations (this is what the CPU is ultimately doing). You can use this method to check any equation to make sure that it is coming out how you expect. It can help you quickly see if your boolean logic is correct for all cases.

Using your equation here is an example:

Replace "true" with 1 and "false" with 0. Replace && with * (as in multiplies) and || with + (as in add). ! does what you expect still. Then check equality so

a*(b+!a) == a*b

Then when a = false (0) and b = false(0) we have

0*(0+1) == 0*0
or  0=0

Which is true.

We can keep going with the other options to check.

a=1, b=1

1*(1+0) == 1*1
or 1=1

again, true

a=1, b=0

1*(0+1) == 1*0
1*1=0?

Not correct (false).

With that last test, we can see that this equation does not always evaluate to true. Just like in math, boolean operations have an order of operations (as mentioned by many others), but I like using this method to make sure my equations are working as intended.