In the case of a Java string, there are some features that must be noted:
--string constants and string pools
--Non-volatile (immutable) strings
1, string constants and string values
Use the following code snippet to illustrate:
String name1 = "Zhangsan";
String name2 = "Zhangsan";
String name3 = new String ("Zhangsan");
String name4 = new String ("Zhangsan");
System.out.println (name1 = = name2);
System.out.println (name1 = = Name3);
System.out.println (Name3 = = name4); The code snippet shows the result of True,false, false, respectively.
Analysis: In Java for efficiency, the "" included strings, string constants (string literal), as long as the content is the same (ordinal, same size), no matter how many times in the program code, the JVM will only create a string instance, and the Maintenance in string pool (string pools) . The first result is true because when the new name1 is created, the JVM creates a string instance that is placed in the strings pool and gives the name1 reference, while the second row is a string instance that lets name2 refer directly to the string pool. As for the later false, because new objects were created at the time, Name3 and Name4 are both references to the newly created string instance.
To use Equals () if you want to compare the object's substance to the same, do not use = =, and use Equals (), and, if you want to compare the actual character of the string to the same content, do not use = =.
2. Non-changeable strings
In Java, once a string object is established, it cannot change anything in the object, and there is no method on the object to change the string contents. How to achieve the connection string with +. For example:
String name1 = "Java";
string name2 = name1 + "World";
System.out.println (name2);
The above program fragment will show Javaworld, because the string content object cannot be changed, so the result is not to add world content directly after the Name1 reference string object. Get after Decompile: Use the + connection string, create the Java.lang.StringBulider object, use its append () method to attach the left and right strings, and then convert to ToString () return.
Summary : Try not to use + connection strings in repetitive situations such as loops or recursion, which can result in a performance burden due to frequent generation of new objects.