Home >Java >javaTutorial >String_string
Immutable String
String objects are immutable. The JVM has optimized it and opened up an area in the memory as a string constant pool. String objects created in "literal" form are cached and reused.
//"字面量"形式创建的字符串 String str = "abc";
String operator: " " and StringBuilder
operator " " can connect String strings. The compiler has an optimization measure. When compiling the source code and finding that all parameters of a calculation expression are literals, it will directly perform the calculation and compile the result into a class file.
String str = "abcd"; String str1 = "ab"+"cd";//输出abcd 对象不变 System.out.println(str==str1);//true
If one side of the calculation expression is a variable, then the compiler will splice it together during runtime and finally generate a new object, consuming performance.
String str = "abcd"; String str1 = "ab"; String str2 = str1+"cd";//输出abcd 对象改变 System.out.println(str==str2);//false
StringBuilder
The compiler will also automatically reference the append() method of StringBuilder for splicing during compilation, and finally call toString() to generate the result. However, each splicing loop in the .calss bytecode will create a StringBuilder object. If the string operation is complex, create a StringBuilder object for splicing when writing the .java file.
Common methods of String
The above is the detailed content of String_string. For more information, please follow other related articles on the PHP Chinese website!