Hi I am studying for an exam and after looking at a past paper I found out that we are being tested on something we haven't been taught in our course.
I don't have a clue how to tackle the question so I am wondering if anyone could explain what kind of method you should use? I don't know anything about maths/logic so idiot-level explanations would be appreciated! All we got taught was that Java has these boolean operators - but no information about how to work with them.
The question is:
Which two Java boolean expressions are equivalent to this expression?
The rule Ralph mentioned is called De Morgan's rule. (Which Wouter already mentioned...)
Now, not everybody knows that one. You could have checked all the possible solutions, limiting your possible values from 0 to 2; anything < 0 is handled by the 0 case, and anything >= 2 is handled by the 2 case. So the original expression would return true only if count == 2. You then check all of the other expressions and check out which other only returns true for count == 2. And that's two: D and E.
A is wrong because of the ||; it would return true for, well, any value of count. Likewise for B. C would return true for only count == 1. F is essentially the same as C.
E is right because it's the direct application of De Morgan's rule:
!((count > 2) || (count <= 1))
is the same as, De Morgan
!(count > 2) && !(count <= 1)
is the same as, && is associative
!(count <= 1) && !(count > 2) (answer E)
is the same as
(count > 1) && (count <= 2) (answer D)
Well actually, there is one flaw in this logic. && is a shortcut operator. That means that the right operand will not be evaluated if the left one is already true. Therefore, the associative swapping isn't always allowed. In this case there is no problem with it though.