State the difference between == operator and equals() method.

Views 16

Answer:

equals() ==
It is a method It is a relational operator
It is used to check if the contents of two strings are same or not It is used to check if two variables refer to the same object in memory
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1.equals(s2);
System.out.println(res);

The output of this code snippet is true as contents of s1 and s2 are the same.
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1 == s2;
System.out.println(res);

The output of this code snippet is false as s1 and s2 point to different String objects.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.