Boolean Operations

The boolean type

The boolean is a primitive data type that has only two possible values: false or true. The default value for this type is false.


    boolean t = true; // t is true
    boolean f = false; // f is false
    boolean defaultValue; // defaultValue is false

Note: Remember, you cannot assign an integer value to a boolean variable. In Java, 0 is not equal to false.

Logical operators

There are four logical operators NOT, AND, OR and XOR which allow us to build logical expressions.

The NOT operator is a unary operator that reverses the boolean value. It is written as !.


    boolean f = false; // f is false
    boolean t = !f; // t is true

The AND operator is a binary operator that returns true if both operands are true, otherwise, it is false. The operator can be written as && and &.


    boolean b1 = false && false; // false
    boolean b2 = false && true; // false
    boolean b3 = true && false; // false
    boolean b4 = true && true; // true

The OR operator is a binary operator that returns true if at least one operand is true, otherwise, it returns false. The operator can be written as ||and |.


    boolean b1 = false || false; // false
    boolean b2 = false || true; // true
    boolean b3 = true || false; // true
    boolean b4 = true || true; // true

The XOR (exclusive OR) operator is a binary operator that returns true if boolean operands have different values, otherwise, it is false. The operator is written as ^ and can be used Instead of the relation operator != (NOT EQUAL TO).


    boolean b1 = false ^ false; // false
    boolean b2 = false ^ true; // true
    boolean b3 = true ^ false; // true
    boolean b4 = true ^ true; // false

Short-circuit operators

The AND and OR operators have two forms: AND ( &, &&), OR ( |, ||).

There are some differences:

In the following example, the second operand a>5 will not be evaluated because the result is determined by the first operand (a==10 is false):


    int a = 20;
    boolean result = (a == 10) && (a > 5); // the second expressions can't be evaluated

The precedence of logical operators

Below the logical operations are sorted in order of their priority in expressions:

  1. ! - NOT
  2. & - AND
  3. ^ - XOR
  4. | - OR
  5. && - conditional AND
  6. || - conditional OR

So, the following statement is true:


    boolean b = true && !false; 
    // true, because !false is evaluated first