1 in general, the comparison of strings in Java is = = comparison reference, equals the practice of comparing values. (Equals is an address compared to other reference types because the Equals method of object compares references), but different methods of declaring method strings are different.
Example: String Str1=new string ("a");
String Str2=new string ("a");
STR1==STR2 Output False
Str1.equals (str2) Output true
And if this statement
String str1= "a";
String str2= "a";
STR1==STR2 Output True
Str1.equals (str2) Output true
This is because the Equals method is also a reference string class in the implementation of the method, the first method of declaring a declaration of two objects, with the ' = = ' comparison is the time to compare the reference output is false because their values are the same as equals when the comparison is a value, Output true.
The second case is not because the comparison has a difference from the first, but because the declaration is different, the second method of declaration has a heap or stack-sharing phenomenon at the time of Declaration, that is, if declared as a class property, he checks that there are no strings in the stack that are identical to the structure that is now declared. If any, direct the address to an existing memory address. Declaring a local variable inside a method works just like he is a stack share.
The corresponding above is an example:
In the first case: (1) Declare a String object str1, which will instantiate an object of type string in memory.
(2) Then declare a String Object str2, which will instantiate another string type object in memory, independent of the first object.
(3) Compare references to two objects, because they are independent of each other so output false
(4) Compare the values of two objects, although they are independent memory areas but have a common memory structure (value), Output true
The second case: (1) declaring a string str1 an object of type string.
(2) declaring another string, now checks for a variable that has no identical memory structure in the same scope, and then directly points to the address if there is one.
(3) = = Compare they have the same address,
(4) equals compares them with the same memory structure (value).
Comparison of strings in Java