The following example is able to demonstrate the point above.
Both s1 and s2 have the same reference in the memory, i,.e. pointing to the same char block in the string pool. meaning that, the same string instance could be re-used as it is found in the string pool. Therefore, both s1 and s2 variables are referred to the same string instance. On this case, "==" may give correct result.
However, for s3 and s4, the s4 has been pointed to a newly created string instance in the heap memory; so on this case s3 and s4 are pointed to different references; "==" test gives a false result, even though s3 and s4 contain the same text content.
So, using equal to method is a safe way to compare two strings, for in this method all char value are compared one by one.
/** * * @author YNZ */ public class StringEqual { public static void main(String ... args){ //string pool, in perm memory String s1 = "hello world"; String s2 = "hello world"; System.out.println(s1==s2); //new string in heap memory String s3 = "i am here"; String s4 = new String("i am here"); System.out.println(s3==s4); } } run: true false BUILD SUCCESSFUL (total time: 0 seconds)