Skip to main content

Groovy : What is Identity Operator and difference between == in Java and Groovy

What is Identity == operator

In Java, == operator is used for checking the reference of objects. In Groovy, it is used to check if the object are equals, i.e it is the implementation of equals() method in java.

== operator in

  1. In java, checks the reference of the objects.
  2. In groovy, == is equivalent to .equals() and checks if the two objects are equal

is operator

  1. In java, does not exist
  2. In groovy, checks the reference of the objects which is == in java

equals() method

  1. In java, checks if the two objects are equal
  2. In groovy, checks if the two objects are equal

Let's have a look at the following examples

class A{
  String name;
  
  boolean equals(A a){
    this.name == a.name
  }
  
}

A a1 = new A(name : 'ekiras')
A a2 = new A(name : 'ekiras')

println (a1 == a2) 
println (a1.equals(a2)) 

The above output will give the following output.

Output

true
true


Comments