Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

playing with java Operators (XOR and AND/OR)

Tags:

java

operators

In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:
- only if any one of the returned value is true and the other is false then I have a problem;
- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?
a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

 // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 { 
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }

2.

  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }


Thanks,
Ivar

P.S: code readability is not an issue. EDIT: I meant to have an XOR in the second option. Also, I agree with the == and != options, but what if I had to use boolean operators?

like image 807
topgun_ivard Avatar asked Dec 07 '22 23:12

topgun_ivard


2 Answers

if (isCorrect(a) != isCorrect(b)) {
  // a OR b is incorrect
} else {
  // a AND b are correct or incorrect
}
like image 153
pingw33n Avatar answered Dec 10 '22 11:12

pingw33n


Your test doesn't need boolean operators, just this:

if (isCorrect(a) == isCorrect(b)) {
    // they both have the same value
} else {
    // they don't ...
}

EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation. In this case the simplest statement of intent is that both a and b obtained the same result.

like image 44
Alnitak Avatar answered Dec 10 '22 13:12

Alnitak