user3541263
user3541263

Reputation: 249

How to check if two boolean values are equal?

I need a method which I can call within the junit assertTrue() method which compares two booleans to check if they are equal, returning a boolean value. For example, something like this:

boolean isEqual = Boolean.equals(bool1, bool2);

which should return false if they are not equal, or true if they are. I've checked out the Boolean class but the only one that comes close is Boolean.compare() which returns an int value, which I can't use.

Upvotes: 8

Views: 60788

Answers (3)

boolean isEqual = !(bool1 ^ bool2);

Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are the same then the XOR operator gives the result '0'.

The XNOR gate is a digital logic gate whose function is the logical complement of the Exclusive OR (XOR) gate.

Upvotes: 0

beresfordt
beresfordt

Reputation: 5222

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class BooleanEqualityTest {

    @Test
    public void equalBooleans() {
        boolean boolVar1 = true;
        boolean boolVar2 = true;

        assertTrue(boolVar1 == boolVar2);
        assertThat(boolVar1, is(equalTo(boolVar2)));
    }
}

Upvotes: 2

The == operator works with booleans.

boolean isEqual = (bool1 == bool2);

(The parentheses are unnecessary, but help make it easier to read.)

Upvotes: 25

Related Questions