Relational Operator in Java with Programming Example

In this chapter you will learn:8325088a1445ee08c9faac1a517e4d59

  1. What is relational operator in Java?
  2. What is the symbol of relational operator?
  3. What does relational operator do?
  4. Programming example of relational operator in Java

What is relational operator in Java?

Relational operator is the operator which compares two operands to check whether it is equal, greater than, less than or not equal to another operands.

Operator Description Example
== equal to: compare two operands and check whether it is equal num1 == num2
!= not equal to: compare two operands and check whether it is not equal num1 != num2
> greater than: compare two operands and check whether left operand is greater than right operand num1 > num2
>= greater than or equal to: compare two operands and check whether left operand is greater than or equal to right operand num1 >= num2
< less than: compare two operands and check whether left operand is lesser than right operand num1 < num2
<= less than or equal to: compare two operands and check whether left operand is lesser than or equal to right operand num1 <= num2
What does relational operator do?

You can say relational operator is comparative operator. When you have two operands and you need to check whether it is equal or not, you need equal to (==) relational operator. Relational operator is mostly used with IF conditional constructs and returns Boolean value (true or false).

Programming Example:

class RelationalOperator
{
  public static void main(String[] args)
  {
    int num1, num2;
    num1=20;
    num2=30;
    
    if(num1==num2)
    {
      System.out.println("num1 is equal to num2");
    }
    if(num1!=num2)
    {
      System.out.println("num1 is not equal to num2");
    }
    
    if(num1<num2) {="" system.out.println("num1="" is="" less="" than="" num2");="" }="" if(num1="">num2)
    {
      System.out.println("num1 is greater than num2");
    }
  }
}

Output

D:\JavaProgram>javac RelationalOperator.java

D:\JavaProgram>java RelationalOperator
num1 is not equal to num2
num1 is less than num2

D:\JavaProgram> __

Summary

In this chapter you have learned what relational operator, their symbol is and how they work. You have also seen a complete programming example demonstrating relational operator. In the next chapter you will learn about logical operator in java.

Leave a Reply

Your email address will not be published.