Difference between equals() and ==

Both equals() and == is used to check the equality of the objects but there is a significance amount of difference between equals() and ==. The equals method is present in the java.lang.Object class and it is used to check the equivalence of the object (ie) to check if the content is equal whereas == is used to check the actual object instances are same or not.

== Operator

The == operator is used to check if both the objects refers to the same place in the memory. Lets see that in the below example

                String str1 = new String("javainterviewpoint");
		String str2 = new String("javainterviewpoint");
		if(str1 == str2)
		{
			System.out.println("Both Objects are equal");
		}
		else
		{
			System.out.println("Both Objects are not equal");
		}

If you have guessed “Both Objects are equal” then you are wrong as == checks for the memory here str1 and str2 are present in a different memory address. Lets assume str1 is at the address and 0x12345 and str2 is at the address 0x23456 that is the reason we are getting “Both Objects are not equal” though the contents are same.

                String str1 = new String("javainterviewpoint");
		String str2 = str1;
		if(str1 == str2)
		{
			System.out.println("Both Objects are equal");
		}
		else
		{
			System.out.println("Both Objects are not equal");
		}

whereas the above code will give you the expected output “Both Objects are equal” as both object refer to the same place in the memory.

equals () method

The equals method checks for the content of both the str objects, we will get “Both Objects are equal” when we compare even the first example with equals().

                String str1 = new String("javainterviewpoint");
		String str2 = new String("javainterviewpoint");
		if(str1.equals(str2))
		{
			System.out.println("Both Objects are equal");
		}
		else
		{
			System.out.println("Both Objects are not equal");
		}

The String class overrides the equals method to compare if the character in the String is equal. So only we are getting true as both holds the same string “javainterviewpoint”.

Leave a Reply

Your email address will not be published. Required fields are marked *