What is difference between == and equals methos in Strings?
>> Monday, May 30, 2011
==: It can be used to compare the reference variables not the content in the String.
Equals():It can be used to compare the string contents .
Just look on the following example:
Equals():It can be used to compare the string contents .
Just look on the following example:
public class StringBasics {
public static void main(String[] args) {
String s1 = new String("A"); //not recommended, use String s1 = "A"
String s2 = new String("A"); //not recommended, use String s2 = "A"
//standard: follows the == and equals() rule like plain java objects.
if (s1 == s2) { //shallow comparison
System.out.println("references/identities are equal"); //never reaches here
}
if (s1.equals(s2)) { //deep comparison
System.out.println("values are equal"); // this line is printed
}
//variation: does not follow the == and equals rule
String s3 = "A"; //goes into a String pool.
String s4 = "A"; //refers to String already in the pool.
if (s3 == s4) { //shallow comparison
System.out.println("references/identities are equal"); //this line is printed
}
if (s3.equals(s4)) { //deep comparison
System.out.println("values are equal"); //this line is also printed
}
}
}
Design Pattern: String class is designed with Flyweight design pattern. When you create a String constant as shown
above in the variation, (i.e. String s3 = “A”, s4= “A”), it will be checked to see if it is already in the String pool. If it is in the
pool, it will be picked up from the pool instead of creating a new one. Flyweights are shared objects and using them can
result in substantial performance gains.
above in the variation, (i.e. String s3 = “A”, s4= “A”), it will be checked to see if it is already in the String pool. If it is in the
pool, it will be picked up from the pool instead of creating a new one. Flyweights are shared objects and using them can
result in substantial performance gains.
0 comments:
Post a Comment