This blog will guide you how to use ‘==’ operator to get appropriate output. Let’s do it with examples, Suppose we have code as given below.

This looks simple and you may guess correct output, once you execute the code you will get the correct output like below -

If you notice that “==” & equals() return different output (we are expecting “true” at line no 7 & 8) but output returns false. Now, the real question why?

  1. Is there any bug in groovy?
  2. Is ‘==’ called equals()?

There are many questions come to your mind but here is the reason why it is happening.

Actually the implementation of “==” in groovy slightly different from Java “==” implementation

Behavior of “==”

In Java,

"==" means equality of primitive types or identity for objects.

In Groovy,

if they are Comparable, "==" translates to "a.compareTo(b)==0"
if they are not Comparable, "==" translates to "a.equals(b)"
	
To check for identity, there is a method "is()". E.g. a.is(b)

Hope this helps

comments powered by Disqus