Question

Please don't look at the condition as they are here to ease the understanding of the behavior

Why does result equals true ?

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

I know we can solve the issue doing:

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

But I am just wondering why the first syntax is incorrect, looks like the '?' operator has more priority over '&&'

Was it helpful?

Solution

The ternary conditional ( ?: ) has lower precedence than &&. So

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

(having unnecessary parentheses); is equivalent to

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

Since (since false && false is false), this reduces to

boolean result = false ? false : true;

which, of course, is true.

OTHER TIPS

  1. && (logical AND)

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

The following list shows all possible combinations:

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

Syntax

expression1 && expression2

Cllick here to know more About Logical AND

  1. || (logical OR)

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

The following list shows all possible combinations:

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

Syntax

expression1 || expression2

Click here to know about Logical OR

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

Because

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

is interpreted as

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

See: Java operator precedence. In the table you can see && has higher precedence than ? :.

it is just some boolean algegra.

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

So in the first case, it is like writting :

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

In your second case, it is like writting :

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top