Equality, Relational, and Conditional Operators In Java

Sometimes we want to compare between operands to determine whether one operand is greater than, less than, equal to, or not equal to another operand. The equality and relational operators help us with this task. This tutorial may also be familiar to you.

To move further let us first know what a conditional test is and how the “if” comes into this picture.

What Is A Conditional Test?

In Java, a conditional test is an expression that results in a boolean value – something that is either true or false. You will come across booleans a lot in programming. The operation of a conditional statement is governed by the outcome of a conditional test that evaluates to either true or false.

In simple words, conditional statements make decisions based upon the outcome of some condition. The if statement is one of Java's conditional statements.
In the simplest form, the if statement allows your program to conditionally execute a statement. The following is the if in its simplest form:
if(expression) statement;
1RrJ6hxwXriMmaZsO73k1EjbgUx0oOrN - Equality, Relational, and Conditional Operators In Java
ic3UokUT0mnOh1RWP531EY2GsMkgg5CmzRkyrgnmWQnf oGal7xW0w K7X hXMWj KsYGUuCenQJ5 Q0T5Qc v24Gvh2iWfhBFIDV4TMy4 JsgFRnA3StNfHtHx9Mm8Lj366wpltyL aeuE iw - Equality, Relational, and Conditional Operators In Java

The expression may be any valid Java expression. The statement(s) will be executed only if the expression evaluates as true. The statement is bypassed if the expression does not evaluate to true, and the line of code following the if is executed.

The expression inside the if compares one value with another using equality or a relational operator commonly. The equality operator checks if the operands are equal or not. On the other hand, a relational operator tests how one value relates to another. The equality and relational operator offered by Java are below.

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

The Equality and Relational Operators

Equality and relational operators are used in Java to compare values and determine the relationship between them. The equality operators are “==” and “!=”, which check whether two values are equal or not equal, respectively. The relational operators are “<“, “>”, “<=”, and “>=”, which compare two values and return true or false depending on whether the relationship between them is less than, greater than, less than, or equal to, or greater than or equal to. These operators are commonly used in decision-making constructs like if-else statements and loops to control the flow of the program based on certain conditions. Understanding how to use these operators effectively is a fundamental skill for Java programming.

The Equality Operators

To test for equality, Java provides the == operator. Yes, there are two equal signs. And there can be no space between them.

Example

10 == 10 evaluates to true,  so the statement followed by the if will be executed in the following EquilityDemo Program. In other words, if we run the EquilityDemo Program, then "true" will be displayed on the console as the conditional test evaluates to TRUE and hence the code followed by the if will be executed.
10 == 11 does not evaluate to true(hence it is false), so the statement followed by the if will not be executed in the following EquilityDemo Program. In other words, if we run the EquilityDemo Program, then "false" will not be displayed on the console as the conditional test does not evaluate to TRUE and hence the code followed by the if will not be executed.
public class EqualityDemo{
    public static void main(String[] args) {
        if(10==10){
            System.out.println("true");
        }

        if(10==11){
            System.out.println("false");
        }
    }
}

Output

true

The Relational Operator

Java uses the > operator to see if one value is greater than another. The outcome of this comparison is, of course, either true or false.

Example

11 > 9 is true . Therefore the "true" will be displayed in the console in the following GreaterThanDemo  program as the statement followed by the if will be executed.
9 > 11 is false . Therefore the "false" will not be displayed in the console in the following GreaterThanDemo  program as the statement followed by the if will not be executed.
public class GreaterThanDemo{
    public static void main(String[] args) {
        if(11>9){
            System.out.println("true");
        }

        if(9>11){
            System.out.println("false");
        }
    }
}

Output

true

Java uses the < operator to see if one value is less than another. The outcome of this comparison is either true or false.

Example

9 < 11 is true . Therefore the "true" will be displayed in the console in the following LessThanDemo  program as the statement followed by the if will be executed.
11 < 9 is false . Therefore the "false" will not be displayed in the console in the following LessThanDemo  program as the statement followed by the if will not be executed.
public class LessThanDemo{
    public static void main(String[] args) {
        if(9 < 11){
            System.out.println("true");
        }

        if(11 < 9){
            System.out.println("false");
        }
    }
}

Output

true
And one other thing - the expression inside the if may be variables. 

For example, the following program stores two values in two variables and determines if the number is positive or negative. 

public class PositiveNegativeDemo{
    public static void main(String[] args) {
        int num1 = 9;
        int num2 = -5;
        if(num1 > 0){
            System.out.println("Num1 is: " + num1);
            System.out.println(num1+ " is positve");
        }

        if(num2 < 0){
            System.out.println("Num2 is: " + num2);
            System.out.println(num2+ " is negative");
        }
    }

}

Output

Num1 is: 9
9 is positve
Num2 is: -5
-5 is negative

The following Java program demonstrates the comparisons in play:

public class ComparisonDemo {

    public static void main(String[] args){
        
        int valueOne = 23;//decalring and intializing a variable
        int valueTwo = 27; //decalring and intializing another variable

        if(valueOne == valueTwo)//Checking if the values are equal
            System.out.println("valueOne == valueTwo");

        if(valueOne != valueTwo)//Checking if the values are not equal  
            System.out.println("valueOne != valueTwo");

        //Checking if the value stored in the first variable is greater than the value stored in the second variable  
        if(valueOne > valueTwo)
            System.out.println("valueOne > valueTwo");

        //Checking if the value stored in the first variable is less than the value stored in the second  variable     
        if(valueOne < valueTwo)
            System.out.println("valueOne < valueTwo");

        /*Checking if the value stored in the first variable is greater than or equal to
         the value stored in second variable*/  
        if(valueOne <= valueTwo)
            System.out.println("valueOne <= valueTwo");
    }
}

Output

valueOne != valueTwo
valueOne < valueTwo
valueOne <= valueTwo

The Conditional Operators

In our previous tutorial, we learned about Relational Operators. The relational operators essentially compare two operands and return a boolean true or false result based on that comparison. To connect true/false results(notice the plural) we use conditional operators. Java has mainly two Conditional Operations: Conditional-AND represented by &&(double ampersands)and Conditional-OR represented by ||(double bars).

                && Conditional-AND 
|| Conditional-OR

Both the operators(and hence the operations) need two operands. The operands are boolean expressions: true or false.

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.

    && evaluates to true if both the operands(two boolean expressions) are true.
    || evaluates to true if one of the operands(two boolean expressions) are true.

Example

int valueOne = 23;
int valueTwo = 27; 
valueOne < valueTwo

The above relational operation evaluates to true.

int valueOne = 23;
int valueTwo = 27;
valueOne == valueTwo

The above relational operation evaluates to false.

Let us denote the first relational operation as o1 and the second relational operation as o2 for simplicity. So, the o1 evaluates to true and o2 evaluate to false. We can connect together true/false results returned(evaluated) by these two relational operations(o1 & o2). This connection operation is done by  && (Conditional-AND) and || (Conditional-OR) operators. So if we want to evaluate the following two conditional expressions:

Expression 1:    if(o1 && o2)
Expression 2:    if(o1 || o2)
Expression 1 evaluates to false as operand o1 is true(as o1 represents relational operation one which evaluates to true) but operand o2(as o2 represents relational operation number two which evaluates to false) is false. We need both the operands to be true for a Conditional-AND operation to evaluate to true.
Expression 2 evaluates to true as operand o1 is true(as o1 represents relational operation one which evaluates to true). We only need one of the operands to be true for a Conditional-OR operation to evaluate to true.

These operators (&& and ||) exhibit  “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

Operator           Action
&&                 AND(Both operands must
                   be true to evaluate to true)
 
||                 OR(One of the operands   
                   must be true to evaluate to true)

!                  NOT(inverts the single
                   operand - true becomes false, false 
                   becomes true)

Suppose in numeric format true is represented by 1 and false is represented by 0. So if one relational expression evaluates to true then the result can be represented by 1. If another relational expression evaluates to false then this result can be represented by 0. The conditional operator performs AND, OR, and NOT(inverts the boolean value – true becomes false and false becomes true ) operations according to the following truth table. The table uses 1 for true and 0 for false.

o1           o2            o1&&o2       o1||o2       !o1

0(false)     0(false)      0            0             1
0(false)     1(true)       0            1             1
1(true)      1(true)       1            1             0
1(true)      0(false)      0            1             0

The precedence of relational and conditional operators is lower than the arithmetic operators. 

This means that expressions like:

10 + value > a + 12

evaluates as if it were written:

(10 + value) > (a + 12)

We earlier mentioned that we connect relational operations together using conditional operators. Any number of relational operations can be linked together using logical operators.

Example

value > max || !(max == 100) && 0 <= item

This expression joins three relational operations:

1. value > max
2. !(max == 100)
3. 0 <= item

The following chart shows the relative precedence of the relational and logical operators:

        Highest!
                >   >=  <   <=
                ==  !=
                &&
        Lowest  ||

The value produced by the relational or conditional operators is either 0 or 1. Even though Java defines true as any nonzero value, the relational and conditional operators always produce the value 1 for true. Your program may make use of this fact.

In professionally written Java code you will almost never come across a statement like this 

if(value != 0).....

The reason is that in Java, true is any nonzero value, and false is zero. There the above-mentioned statement is generally written as this:

if(value)...

Further, statements like this

if(value == 0)...

are written as

if(!value)

The expression !value is true only if the value is zero.

The following program demonstrates what we have learned so far. Remember, the outcome of a relational/conditional operation is 0 when false and 1 when true. The following program defines two variables, requests two integers, stores them in the variables, and then displays the outcome of each relational and conditional operation when applied to them. In all cases, the result will be a 0 or 1.

Source Code:

import java.util.Scanner;

class ConditionalDemo1 {

    public static void main(String[] args){
        //declare two variables
        int valueOne;
        int valueTwo;

        //take inpur from the keyboard and store the values in the variables
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter first number : ");
        valueOne = scan.nextInt();

        System.out.println("Enter second number : ");
        valueTwo = scan.nextInt();

        scan.close();

        //relational operations
        if(valueOne == valueTwo)
            System.out.println("valueOne == valueTwo");
        if(valueOne != valueTwo)
            System.out.println("valueOne != valueTwo");
        if(valueOne > valueTwo)
            System.out.println("valueOne > valueTwo");
        if(valueOne < valueTwo)
            System.out.println("valueOne < valueTwo");
        if(valueOne <= valueTwo)
            System.out.println("valueOne <= valueTwo");

        //condtional operations
        if((valueOne == 1) && (valueTwo == 2))
            System.out.println("valueOne is 1 AND valueTwo is 2");
        if((valueOne == 1) || (valueTwo == 1))
            System.out.println("valueOne is 1 OR valueTwo is 1");
        
      
    }
}

Output : 

Enter first number :
2
Enter second number :
3
valueOne != valueTwo
valueOne < valueTwo
valueOne <= valueTwo
Enter first number :
1
Enter second number :
2
valueOne != valueTwo
valueOne < valueTwo
valueOne <= valueTwo
valueOne is 1 AND valueTwo is 2
valueOne is 1 OR valueTwo is 1

Summary of Operators

The following quick reference summarizes the operators supported by the Java programming language.

Simple Assignment Operator

=       Simple assignment operator

Arithmetic Operators

+       Additive operator (also used for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%       Remainder operator

Unary Operators

+       Unary plus operator; indicates positive value (numbers are positive without this, however)
-       Unary minus operator; negates an expression
++      Increment operator; increments a value by 1
--      Decrement operator; decrements a value by 1
!       Logical complement operator; inverts the value of a boolean

       

Equality And Relational Operators

==      Equal to
!=      Not equal to
>       Greater than
>=      Greater than or equal to
<       Less than
<=      Less than or equal to

Conditional Operators

&&      Conditional-AND
||      Conditional-OR

ADDING THE ELSE

If we add an else statement to the if statement then the if statement looks like this :

if(expression) {
                    statement1;
}else{
                    statement2;
}

The code following the if(statement1) will execute if and only if the expression is true. And the else portion will be skipped. 

If the expression is false then the code following else(statement2) is executed and the code following the if is bypassed. Under no circumstances will both statements execute. Thus, the addition of the else provides a two-way decision path. 

You can create more efficient code using the else. For example, in the following program, the else is used in place of a second if, which determines whether a number is negative or non-negative.

public class PositiveNegativeDemo2{
    public static void main(String[] args) {
        int num1 = 9;
        int num2 = -5;
        if(num1 > 0){
            System.out.println("Num1 is: " + num1);
            System.out.println(num1+ " is positve");
        } else{
            System.out.println("Num2 is: " + num2);
            System.out.println(num2+ " is negative");
        }
    }
}

Output:

Num1 is: 9
9 is positive

Recall that the first version of this program explicitly tested for non-negative numbers by comparing num2 to -1 using a second if statement. There is no reason for this second test as there are only two possibilities – num2 is either negative or non-negative. We can use else.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.