First, we need to figure out that in Java, references and basic data types are stored in the stack. The objects are stored in the heap.
There is only one exception, the string object.
For example:
String str1= "Test"; String str2= "Test"; String Str3=new string ("Test1"); String Str4=new string ("Test1"); System.out.println (STR1==STR2); System.out.println (STR3==STR4);
For STR1 and str2, the object "test" they refer to is neither in the stack nor in the heap. Instead, it is stored in a string pool.
There is only one "test" in the string, which means that no matter how many str= "test" you declare, only one copy is stored in the string pool, and all str points to the same address.
And the situation of STR3,STR4 is not the same.
STR3 and STR4 Use the new keyword to generate objects, and objects generated by the new keyword are stored in the heap, so str3 and STR4 are pointing to two different objects.
Therefore, the output of the above program is
True
False
Reference: http://sarin.iteye.com/blog/603684/
Several problems of String class in Java