Java relational operator

Relational Operators in Java Programming :

  1. Relational Operators are used to check relation between two variables or numbers.
  2. Relational Operators are Binary Operators.
  3. Relational Operators returns “Boolean” value .i.e it will return true or false.
  4. Most of the relational operators are used in “If statement” and inside Looping statement in order to check truthness or falseness of condition.

relational operator in java programming
[468x60]

We can use Relational Operators in multiple ways -

  1. Inside Condition for checking whether condition is true or false.
  2. Inside Expression.
OperatorResult
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
[468x60]

Live Example 1 : Comparison Operator Demo

class ComparisonDemo {
    public static void main(String[] args){
        int ivar1 = 1;
        int ivar2 = 2;
        if(ivar1 == ivar2)
            System.out.println("ivar1 == ivar2");
        if(ivar1 != ivar2)
            System.out.println("ivar1 != ivar2");
        if(ivar1 > ivar2)
            System.out.println("ivar1 > ivar2");
        if(ivar1 < ivar2)
            System.out.println("ivar1 < ivar2");
        if(ivar1 <= ivar2)
            System.out.println("ivar1 <= ivar2");
    }
}

Output :

ivar1 != ivar2
ivar1 <  ivar2
ivar1 <= ivar2

Some Must Remember Notes : Be aware of it

1 . Do not Use Relational Operator to Initialize Non-Boolean Variable

Consider Following Program -

class boolDemo
{
public static void main(String args[])
  {
  int num1 = 100 > 20;
  System.out.println(num1);
  }
}

In this situation , we cannot use relational operator in the expression like C Programming If you are coming from C/C++ background then you must throw your habit of using relational operator inside expression.

Following Code will run -

However we can use Relational Operators in Expression in which final result will be accumulated in boolean variable.

class boolDemo
{
public static void main(String args[])
  {
  boolean num1 = 100 > 20;
  System.out.println(num1);
  }
}

Output :

true

2 . Do not use just variable name of non-boolean data type inside if

class boolDemo
{
 public static void main(String args[])
  {
  boolean num1 = true;
  if(num1)
     {
     System.out.println(num1);
     }
  }
}

Output :

true

however if you try this following program then you will definitely get an error -

class boolDemo
{
 public static void main(String args[])
  {
  int num1 = 10;
  if(num1)
     {
     System.out.println(num1);
     }
  }
}

Output :

C:code>javac hello.java
hello.java:7: incompatible types
found   : int
required: boolean
  if(num1)
     ^
1 error

Conclusion :

  • If you are using Relational Operator in expression then use “Boolean” Variable at Left hand side.