Relational Operators

These Operators are used for the purpose of comparing values.

  1. >(greater than operator)
  2. >=(greater than or equal to operator)
  3. < (less than operator)
  4. <=(less than or equal to operator)
  1. Relational Operators are applicable only for primitive types except boolean.

    Example:

    public class Test {
     public static void main(String[] args) {
    	 System.out.println(10>20);//false
    	 System.out.println(10>10.0);//false
    	 System.out.println('a'>'z');//false
    	 System.out.println(10.123>10);//true
    	 System.out.println(true>false);//Compile time error
    	 System.out.println("Arch">"Arch123");//Compile time error
     }
    }
    
  2. we can not perform nesting of relational operator:

    public class Test {
     public static void main(String[] args) {
       System.out.println(10<20<30);//Compile time error
       System.out.println(10<20);//true
     }
    }
    
  3. Equality Operators(==,!=)

    Example:

    
    public class Test {
     public static void main(String[] args) {
    	System.out.println(10==20);
    	System.out.println('9'==98);
    	System.out.println(10==10.0);
    	System.out.println(true==true);
     }
    }
    /*
    Output:
    false
    false
    true
    true
    */
    
    1. We can apply equality operators even for object references also
    2. r1==r2 returns true, if and only if both r1 and r2 pointing to the same object on the heap.i.e ‘==’ operator is always mean for reference comparision

      Example:

      public class Test {
       public static void main(String[] args) {
      	Thread t1=new Thread();
      	Thread t2=new Thread();
      	Thread t3=t1;
      	System.out.println(t1==t2);
      	System.out.println(t1==t3);
       }
      }
      /*
      false
      true
      */
      

      Output:
      false
      true

    3. To use the == operator, there should be some relation b/n the types of r1 and r2 (either parent to child/child to parent/same type), otherwise we will get compile time error saying “Incomparable types”
    4. Example:

      
      public class Test {
        public static void main(String[] args) {
          String s1=new String("Arch");
          StringBuffer s2=new StringBuffer("Arch");
          Object s3=new Object();
          System.out.println(s1==s2);//incomparable types
          System.out.println(s1==s3);//false
        }
      }
      
    5. For any object reference r,(r==null) is always false.