It is important to understand that the equals( ) method and the == operator perform two different operations.
For String class
equals() | Compares the characters inside a String object, i.e.) it compares the contents of the String object. |
== operator | Compares two references to see whether they refer to the same object in the memory |
Example 1:
package com.ibytecode.strings.methods; public class EqualsAndEqualToOperator { public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; if(s1.equals(s2)) System.out.println("s1.equals(s2) is True"); if(s1 == s2) System.out.println("s1 == s2 is True"); } }
s1.equals(s2) is True
s1 == s2 is True
As already explained in string literal pool JVM creates a new String object in constant pool and makes s1 refer to it. Now for creating s2, it checks the String constant pool and since the string already exists a reference to the pooled instance is returned to s2.
Hence the above code creates,
- Two references, s1 and s2
- One String object “abc”
Example 2:
package com.ibytecode.strings.methods; public class EqualsAndEqualToOperator { public static void main(String[] args) { String s3 = "abc"; String s4 = new String("abc"); if(s3.equals(s4)) System.out.println("s3.equals(s4) is True"); if(s3 == s4) System.out.println("s3 == s4 is True"); else System.out.println("s3 == s4 is False"); } }
s3.equals(s4) is True
s3 == s4 is False
The above code creates,
- Two references, s3 and s4
- Two String objects “abc” in literal pool and one string object “abc” on heap
Refer string literal pool tutorial for more datails
Example 3:
package com.ibytecode.strings.methods; public class EqualsAndEqualToOperator { public static void main(String[] args) { String s5 = new String("abc"); String s6 = new String("abc"); if(s5.equals(s6)) System.out.println("s5.equals(s6) is True"); if(s5 == s6) System.out.println("s5 == s6 is True"); else System.out.println("s5 == s6 is False"); } }
s5.equals(s6) is True
s5 == s6 is False
Example 4:
package com.ibytecode.strings.methods; public class EqualsAndEqualToOperator { public static void main(String[] args) { String s7 = new String("abc"); String s8 = new String(s7); if(s7.equals(s8)) System.out.println("s7.equals(s8) is True"); if(s7 == s8) System.out.println("s7 == s8 is True"); else System.out.println("s7 == s8 is False"); } }
s7.equals(s8) is True
s7 == s8 is False