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

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 will 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

NOTE:

  • For array, string or arraylist object reference obj, obj == null is always false. But null == null is always true.

Here’s the complete example for difference between == and equals method in java ,

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

Please keep in mind that equals method of Object class can also be used for comparing reference based on requirement.

Related Posts