Equality Operator

Equality Operator (= =), (!)

We can apply equality operators for all primitive data types including boolean also.

  • 10 = = 20 ; // true
  • ‘ a ‘ = = 97 ; // true
  • 10 = = 10.0 ; // true
  • true = = true ; // true

We can apply equality operators even for object reference also ‘ r1 = = r2 ‘ is true if and only if both are pointing to same object.

  • thread t1 = new thread ( ) ;
  • thread t2 = new thread ( ) ;
  • thread t3 = t1 ;
  • s.o.p ( t1 = = t2 ) ; // false
  • s.o.p ( t1 = = t3 ) ; // true

If we won’t to apply = = operator there should be some relationship  b/n the argument type otherwise we will get compile time error.

  • exception e = new exception ( ) ;
  • thread t1 = new thread ( ) ;
  • s.o.p ( e = = t1 ) ; ( compile time error )

—> in comparable types thread, exception.

—> consider the following types.

  • Object o = new Object ( ) ;
  • String s = new String ( ) ;
  • StringBuffer sb = new StringBuffer ( ) ;

Que:- Which of the following expressions are valid ?

  1. o1 = = s 1
  2. o1 = = s 2
  3. s 1 = = s 2 ( compile time error)
  4. All the above

Ans:- 1, 2 .

For any Object reference r , ” r = = null ” is always false.

Note:-
In general ” = = ” operator always meant for reference comparison. Where as equals ( ) method for content comparison.
  • s.o.p ( null = = null ) ; // true
  • String s1 = new String ( ) ;
  • String s2 = null ;
  • s.o.p ( s1 = = null ) ; // false
  • s.o.p ( s2 = = null ) ; // true
  • s.o.p ( null = = null ) ; // true
  • s.o.p ( s1 = = s2 ) ; // false

Leave a Reply