Boolean operator precedence


#1

Can someone explain why this code prints false?

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

#2

I mean.. evaluate the operators and see for yourself, right? If there's a problem in doing so, then perhaps that is something that you can ask about
If you don't think it should print false, then motivate why you think it should be printing true and in so doing making it very easy to point out where you go wrong (put in some effort to make it easy to reply)


#3

I just wanted to know the precedence, I guess everything between the !( ) equals false?


#4

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
google is your friend

not false is true, you just suggested that it prints false


#5

wait a second.. i want to understand this as well.

from my understanding the Order is ! 1< 8 is done first so that equals False..

Next is 1 < 8 && 5> 2 so that equals True..

And last you have 5 > 2 || 3 < 5 which is True..

Plugged in... False && True || True..
False && True = False
True || True = True

Again.. False || True = True.. This is what im getting which is clearly wrong. but when you run it its False.. the correct answer.. mind explaining it?


#6

Looking at this code from the OP:

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

(5 > 2 && 3 < 5) = TRUE. 5 is greater than 2 and 3 is less than 5.
1 < 8 = TRUE. 1 is less than 8.
(TRUE || TRUE) = TRUE
!(TRUE) = FALSE
So...it's False.

Remember anything in brackets are evaluated first.


#7

WOW... i failed to understand all because of a basic rule i was completely overlooking / forgetting. --______--

Thank you for pointing that out.. i was legit feeling really dumb.


#8

Thank you for explaining this! Now I understand it.


#9

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