Wednesday 27 September 2023

Difference between equals method and == operator in java

      In this post, we can discuss one of the important java interview questions i.e difference between equals() and == operator and sample examples.

equals and == operator in java

The equals() method compares the content of two objects but == opeator checks the objects references of two objects for equality.

Let me see few examples to check both equals and == operator,

  • Created two string objects using new operator and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = new String("A");
	  String s2 = new String("A");

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:- 
s1 equals s2 are equal
s1 == s2 are not equal

Used new operator to create String objects and those objects will store in heap memory of JVM and will create two different objects in the heap even the contents are same. So == operator result will return false.
  • Created two string objects using literal and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = "A";
	  String s2 = "A";

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:-

s1 equals s2 are equal
s1 == s2 are equal

Youtube Video:-


Thank you for visiting blog.

No comments:

Post a Comment