Q1. What is the difference between “==” and “equals(…)” in comparing Java String objects? (JNNC Technologies)


Q1. What is the difference between “==” and “equals(…)” in comparing Java String objects?

A1. When you use “==” (i.e. shallow comparison), you are actually comparing the two object references to see if they point to the same object. When you use “equals(…)”, which is a “deep comparison” that compares the actual string values. For example:



1
2
3
4
5
6
7
8
9
10
11
12
13
public class StringEquals {
public static void main(String[ ] args) {
   String s1 = "Hello";
   String s2 = new String(s1);
   String s3 = "Hello";
   System.out.println(s1 + " equals " + s2 + "--> " +  s1.equals(s2)); //true
   System.out.println(s1 + " == " + s2 + " --> " + (s1 == s2)); //false
   System.out.println(s1 + " == " + s3 + " -->" + (s1 == s3)); //true
}
}

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are 2 distinct objects having 2 distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value “Hello”. The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.




Computer Training Institute in Vizag JNNC Technologies Pvt.Ltd Software Training Institute in Vizag JNNC Technologies Pvt.Ltd

Post a Comment

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();