Why false && (false)? False: true return true

Please do not look at the condition, as they are here to facilitate understanding of behavior.

Why is the result true?

boolean result = false && (false)?false:true; 

I know that we can solve the problem:

 boolean result = false && (false?false:true); 

But I'm just wondering why the first syntax is wrong, looks like '?' operator takes precedence over '& &'

+6
source share
5 answers

Triple conditional ( ?: Has a lower priority than && . So,

 boolean result = false && (false)?false:true; 

(with extra brackets); equivalently

 boolean result = (false && false) ? false : true; 

Since (since false && false is false ), it comes down to

 boolean result = false ? false : true; 

which of course is true .

+11
source

false && (false) evaluates to false , so the last value of the ternary operator is returned, i.e. true .

+6
source

1) && (logical AND)

Description: - Compares two expressions and returns true only if both evaluate to true. Returns false if one or both is false.

The following list shows all possible combinations:

 true && false // Evaluates false because the second is false false && true // Evaluates false because the first is false true && true // Evaluates true because both are true false && false // Evaluates false because both are false 

Syntax

expression 1 && expression 2

Cllick is here to learn more about logic and

2) || (logical OR)

Description: - compares two expressions and returns true if one or both evaluates to true. Returns false only if both expressions are false.

The following list shows all possible combinations:

 true || false // Evaluates true because the first is true false || true // Evaluates true because the second is true true || true // Evaluates true because both are true false || false // Evaluates false because both are false 

Syntax

expression1 || expressions2

Click here for logical OR

+4
source

Because the

 boolean result = false && (false)?false:true; 

interpreted as

 boolean result = (false && (false))?false:true; 

See: Java operator priority . In the table, you can see that && has a higher priority than ? : ? : .

+2
source

it is just logical algebra .

 False && false = true false && true = false true && true = true true && false = false 

So, in the first case, it is like writing:

 if (false && false){ result = false } else { result = true } 

In your second case, this is like spelling:

 result = false && (false == false); 

and false == false returns true. So false && true returns false

0
source

Source: https://habr.com/ru/post/953780/


All Articles