Labido
Labido

Reputation: 1

Why does this return true?

I recently started to teach myself Java, after playing around with CodingBat I am left with an extremely basic question. Why is this returning "true"?

a = 1, b= -1, negative = true

public boolean posNeg(int a, int b, boolean negative) {
  if(!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0){
    return true;
  }else if(negative && a <= 0 && b <= 0){
    return true;
  }
  return false;
}

Upvotes: 0

Views: 106

Answers (3)

Trevor
Trevor

Reputation: 2932

In your first if if(!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0){ A is greater than 0, and b is less than 0, so return true.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140514

In:

!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0

the higher precedence of && than || means it is the same as:

(!negative && a <= 0 && b >= 0) || (a >= 0 && b <= 0)

The conditional-or operator (||) will return true if either of its operands are true:

  • !negative && a <= 0 && b >= 0 is false, because negative is false (as is b >= 0, but that's not evaluated);
  • a >= 0 && b <= 0 is true

Hence the expression is true, and so the if statement is executed, meaning that true is returned.

Upvotes: 7

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

because :

if (!negative && a <= 0 && b >= 0 || a >= 0 && b <= 0) {
//---(false)------(true)----(false)-----(true)----(true)

The trick is with || :

false && true && false -> false
true && true -> true

(false && true && false) || (true && true) ----> true
     false               ||     true       ----> true

Upvotes: 2

Related Questions