Java’s arithmetic operators, such as +, -, *, /, perform calculations on numeric data types and return a numeric value and are the building blocks of arithmetic expressions. In this article, we cover another category of operations that perform logical comparisons. Logical operators are the building blocks of boolean expressions, which can be evaluated to a boolean value that is either true or false.

As you can imagine, boolean expression are useful for branching statements in our program. For example, if certain boolean condition is true, our program should do this; otherwise, the program should do something else. In fact, boolean expressions are used in conditional statements, such as if-else statement, and looping statements, such as while loop. These control statements will be covered in succeeding articles.

Comparison Operators

A simple true-false expression is just comparing two things. Do do so, we use Java’s comparison operators below, assuming a = 3 and b = 4.

Operator Meaning Example
== equal to `a == b` is false
!= not equal to `a != b` is true
< less than `a < b` is true
<= less than or equal to `a <= b` is true
> greater than `b > b` is false
<= greater than or equal to `b <= b` is true

These comparison operators can be used for all built-in data types and behave as expected most of the time. One must be very careful when comparing a variable of float-point type (float and double) against a literal, due to impreciseness of float-point encoding.

These operators can also be used to compare variable of reference types (objects); however, when used, these operators performs reference (address) comparison. For example, given two objects a and b, a == b is true only if a and b are the same object in memory, regardless of object’s content. For this reason, objects are usually compared using equals() method, or using implementation of Comparable and Comparator interfaces.

Logical Operators

In addition, Java has following logical operators.

Operator Meaning True if Example
! not operand is not true (truth reversal) `(!true)` is false
&& and both operands are true `(true && false)` is false
|| or one or both operand is true `(true || false)` is true
^ xor only one operand is true, not both `(true || true)` is false

## Examples

public class BooleanExpressionExample
{
    public static void main(String[] args)
    {
        int a = 1;
        int b = 2;
        boolean x = false;

        x = a > 0 && b > a;    //x -> true
        x = a > 0 && b < a;    //x -> false
        x = a > 0 || b < a;    //x -> true
        x = (a > 0) ^ (b > a); //x -> false
        x = (a > 0) ^ (b < a); //x -> true
        x = (a < 0) ^ (b < a); //x -> false
    }
}

Operator Precedence

The following list is the order of operation of conditional operators, top ones before bottom ones.

Operator Description
! not
==, != equality
^ xor
&& and
|| or
= assignment

For a complete list of operators and their precedence please see Java Operator Precedence.