Someone help me explain Boolean Operators

Can someone help me explain the code below pls
What meaning of Boolean operators “&&”, “||”, and “!” ?

public class Precedence {
	public static void main(String[] args) {

		boolean riddle = !( 1 < 8 && (5 > 2 || 3 < 5));


How did you arrive at the solution, given the above question? Copy and paste?

&&  stands for Boolean AND

||  stands for Boolean OR

!   stands for Boolean NOT

Do you understand these operations?


Yes, I reveal the correct solution and copy and paste it here after I got no ideas.

Actually I understand what each symbol do but I don’t really know how to apply them in the code above.

Then my only conclusion can be that there is a deficiency of understanding. Sorry.

1 Like

It’s ok, thx for your answering :slight_smile:

Let me try to explain this :smiley:
boolean riddle = !( 1 < 8 && (5 > 2 || 3 < 5));

The || operator executes when one or both conditions are true, in this case both conditions are true and the boolean returns true. Then java moves to the outer bracket. 1<8 is true AND (5>2||3<5] is true so the whole bracket equals a true boolean. The -> ! <- operator negates everything in the brackets, which is why your output is “false”.
I hope that helped you at least a bit, I’m also a beginner which is why this is the best explanation i can offer you :slight_smile:

1 Like

There is no or both since OR short-circuits on True. Only one condition needs to be true and the other is ignored.

true || true  => only the first operand is evaluated

true || false => likewise

false || true => only now is the second operand examined

All above are true.

It is not enough to just know what AND, OR, NOT mean. We must be aware of operator precedence, similar to order of operations in maths.

The above expression contains, brackets, comparisons, and logic which also has precedence, NOT, AND, OR in that order when there are no brackets.

!( 1 < 8 && (5 > 2 || 3 < 5));

Inner brackets take precedence, and then comparison comes next. 5 > 2 || 3 < 5 sort-circuits on 5 > 2. 3 < 5 is not evaluated. Rewriting gives,

! ( 1 < 8 && true )

Again, comparison takes precedence, so 1 < 8 is evaluated, yielding true, so,

! (true && true)

which we know is ! true, or false.


Very good explanation, should be your first comment on this post! :smiley:


Perhaps you are right. The OP needed clarification, though, so it was necessary to break some eggs. The question was posted with letter perfect code which is a bit suspect. Learners need to know that they have to put their foot forward first when it comes to effort, which in this case seemed sorely lacking. Had it not been for your atempt at answering, this thread would probably have died on the operating table.


That is very understandable. Basically saying !(true) = false. Reason to that is because != NOT.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.