4

Difference between equals method and == operator in java

 9 months ago
source link: http://adnjavainterview.blogspot.com/2023/09/difference-between-equals-method-and-operator-in-java.html.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK