First Look at a program
Packagereverse; Public classReverse { Public Static voidMain (string[] args) {String C1=NewString ("ABC"); String C2=NewString ("ABC"); String C3=C1; System.out.println ("C1==C2:" + (c1==C2)); System.out.println ("C1.equals (C2):" +c1.equals (C2)); System.out.println ("C3==C1:" + (c3==C1)); System.out.println ("C1.equals (C3):" +C1.equals (C3)); C1= "Han"; SYSTEM.OUT.PRINTLN (C1+" "+C3); System.out.println ("" + (c3==C1)); }}
The first output statement c1==c2 well, because both C1 and C2 are references to objects created with new, although the values of the objects are the same, but two objects are in different memory spaces, that is, C1 and C2 are references to two different objects, so the result is false. The second output statement, c1.equals (C2), is the Equals method that invokes the string class, which is used to compare the values of two string objects for equality, so the result is true.
C1, c2 variables in-memory emulation:
True for C3==C1 is because assigning the C1 to C3 is a reference to the C1 object that assigns the C3;c1 and C3 in-memory impersonation:
For System.out.println (c1+ "" +c3), this output statement would ask that since C1 and C3 refer to the same object, why is the value of C1 changed without change?
This involves the immutability of string objects in Java, what is immutable, the simple thing is that once a string object is created and assigned (initialized) the value of the object does not change.
Once a string object is created in memory, it will be immutable, and all of the methods in the string class do not change the string object itself, but instead recreate a new string object.
In other words, C1=han, instead of changing the value of the original object, creates a new string object with a value of Han and assigns the reference to the object to C1.
At this point C1 and C3 in-memory simulations:
So at this point c1==c3 is False
Because of the immutability of the string object, if you need to make a large number of modifications to the string, add characters, delete characters, and so on, try not to use the string object, because it will frequently create new objects resulting in inefficient execution of the program
At this point we can use the string generator StringBuilder.
Immutability of String objects in Java