Equality, Relational, and Conditional Operators

Ref#. CS-JAVA-CODE-02

License: This work is licensed under a Attribution 4.0 International.

The Equality and Relational Operators

These are the signs used to compare something, like two numbers. Take note that some of them are different from what we use in math. We use != in java to represent not equal to, and use == instead of a single = sign to represent an equal relationship.

==      equal to
!=      not equal to
>       greater than
>=      greater than or equal to
<       less than
<=      less than or equal to

The following program uses these methods to compare which one of the two numbers is larger.

class test {

    public static void main(String[] args){
        int number1 = 1;
        int number2 = 2;
        if(number1 == number2)
            System.out.println("number1 == number2");
        if(number1 != number2)
            System.out.println("number1 != number2");
        if(number1 > number2)
            System.out.println("number1 > number2");
        if(number1 < number2)
            System.out.println("number1 < number2");
        if(number1 <= number2)
            System.out.println("number1 <= number2");
        if(number1 >= number2)
            System.out.println("Number1 is larger than number 2.");
    }
}

Output:

number1 != number2
number1 <  number2
number1 <= number2

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND
|| Conditional-OR

The following program demostrates the method above.

class test2 {

    public static void main(String[] args){
        int number1 = 1;
        if((number1 >0) && (number1 !=1))
            System.out.println("number1 is larger than zero and does not 
            equal to 1");
    }
}