Difference between “==” and equals method in java

Hey guys!! Welcome to flower brackets blog. Let’s learn the difference between “==” and equals method in java.

Difference between "==" and equals method in java

Difference between “==” and equals method in java

In general we use == operator for reference comparison. Because in java we don’t have concept of operator overloading. Meanwhile equals() method is used for checking equality of two objects.

Equality (==) operator returns true only, if two objects is pointing to same object else return false. Also == operator is used to compare primitive data types (float, boolean, integer) and objects.

Also read – java compare strings

Object.equals() method returns true only, if two objects have same value. Let’s say, if two Students have same studentID then they are considered equal.

Example:

// == operator
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // output : false

// equals() method
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // output : true

Let’s compare strings using “==” and equals method,

public class OperatorVsMethod 
{
public static void main(String[] args)
{
String str1 = new String("HelloWorld");
String str2 = new String("HelloWorld");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
String str3 = new String("HelloWorld");
System.out.println(str3 == null);
String str4 = null;
System.out.println(str4 == null);
System.out.println(null == null);
}
}

Output:

false
true
false
true
true

Now let’s compare two objects using “==” and equals method,

public class ComparisonDemo 
{
   public static void main(String[] args) 
   {
      Object ob1 = new Object();
      Object ob2 = new Object();
      boolean output;
      output = (ob1 == ob2);     System.out.println("== operator : " + output);
      output = ob1.equals(ob2);     System.out.println("equals() method : " + output);
      ob1 = ob2;
      output = (ob1 == ob2);
      System.out.println("Compare two reference pointing to same Object using == operator : " + output); }
   }
}

Output:

== operator : false
equals() method : false
Compare two reference pointing to same Object using == operator : true

NOTE:

  • equals method of Object class can also be used for comparing reference based on requirement.
  • equals() method is a method while “==” is an operator.

Related Posts