In java, we have two operations ("==" and "equals()") to check the equivalence of Strings. It is important to understand that the difference between them.
==
The == operator compares the two objects and checks to see if two objects are exactly the same object (refer to the same instance).
.equals()
The equals() method compares the characters in the two different objects. Two strings may be different objects, but can contains the same values (exactly the same characters).
The output of the above code is:
However, please compare the following code segment with the above code:
The output of this code will be:
It is caused by the JVM optimization. When JVM detect two constant strings with the same content, it will optimize the the two constant strings to one copy to save memory. Therefore, the two string references will refer to the same object.
==
The == operator compares the two objects and checks to see if two objects are exactly the same object (refer to the same instance).
.equals()
The equals() method compares the characters in the two different objects. Two strings may be different objects, but can contains the same values (exactly the same characters).
public class Main { public static void main(String[] args) { String s1 = "Shangshu"; String s2 = new String(s1); System.out.println(s1 + " == " + s2 + " is " + (s1 == s2)); System.out.println(s1 + ".equals(" + s2 + ") is " + (s1.equals(s2))); } }
The output of the above code is:
Shangshu == Shangshu is false Shangshu.equals(Shangshu) is true
However, please compare the following code segment with the above code:
public class Main { public static void main(String[] args) { String s1 = "Shangshu"; String s2 = "Shangshu"; //new String(s1); System.out.println(s1 + " == " + s2 + " is " + (s1 == s2)); System.out.println(s1 + ".equals(" + s2 + ") is " + (s1.equals(s2))); } }
The output of this code will be:
Shangshu == Shangshu is true Shangshu.equals(Shangshu) is true
It is caused by the JVM optimization. When JVM detect two constant strings with the same content, it will optimize the the two constant strings to one copy to save memory. Therefore, the two string references will refer to the same object.
Comments