The difference between the String and StringBuffer and StringBuilder, Java 1.1 introduces commonly used for dealing with strings in Java has three categories: 1, Java. Lang. String 2, Java. Lang. StringBuffer 3, Java. Lang. In common: StrungBuilder three are final class, are not allowed to be inherited, mainly from the consideration on the performance and security, Because these classes are often used, and to prevent the parameters of the parameter change affect other applications.

StringBuffer is thread-safe and can be used in multiple threads without additional synchronization; StringBuilder is asynchronous, running in multiple threads requires separate synchronization processing, but is much faster than StringBuffer; StringBuffer and StringBuilder have something in common: strings can be manipulated by append, insert, deleteCharat, and so on. The usage is the same. String implements three interfaces Serializable Comparable CarSequence StringBuilder implements only two interfaces Serializable CharSequence In contrast, instances of String can be compared using the compareTo method; the other two cannot. A String is a String constant that is a reference type. Once created, the String is immutable. In the case of a String, a new String object is returned if the String type is changed. Char []: char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] : char[] Let’s look at an example:

String s = “Hello World”;

When creating a string constant, the JVM first checks the string constant pool. If the string “Hello World” exists in the string constant pool, it assigns the address of the string object to the reference S (which is stored on the stack). If the string is not in the constant pool, the string is created in the constant pool, and the address value of the string object is given to S. It is important to note that only 1 or 0 string objects are created (if the Hello World constant pool already exists, it will not be created). Let’s look at the next example: String s = new String(“Hello Java”);

When creating a string constant, the JVM first checks the string constant pool. If the string “Hello Java” already exists in the constant pool, it directly copies a copy of the object in the heap, and assigns the address value in the heap to the reference S. No object is created in the string constant pool. If the string does not exist in the constant pool, the string is instantiated and placed in the constant pool, then a copy of the object is made in the heap, and the address value of the object is given to S. Note that two string objects are created, one in the constant pool and one in the heap (regardless of the fact that the object already exists). The differences between these three classes are mainly in two areas: speed and thread safety. StringBuilder > stringBuffer > String String String String String String String String String String String String String is a String constant, while StringBuilder and StringBuffer are String variables, meaning that a String object cannot be changed once it is created, but the objects of the latter two are variables and can be changed. Take the following code as an example:

String str=”abc”;

System.out.println(str);

str=str+”de”;

System.out.println(str);



If you run this code, you’ll see that it prints “ABC” and then “ABCDE” as if the object has been changed. In fact, this is just an illusion. The JVM does this by creating a String called STR and assigning “ABC” to STR. The JVM creates a new object named STR, adds the value of the original STR to the value of “de”, and aspoints it to the new STR. The original STR is collected by the JVM’s garbage collection mechanism (GC), so the STR is not actually changed. Once a String is created, it cannot be changed. As a result, the operation on strings in Java is actually a slow process of constantly creating new objects and recycling old ones.

StringBuilder and StringBuffer, on the other hand, are variables. Operating on variables is to change the object directly without creating or retrieving it, so it is much faster than StringBuffer. In addition, we sometimes assign strings like this:

String str=”abc”+”de”; StringBuilder stringBuilder=new StringBuilder().append(“abc”).append(“de”); System.out.println(str); System.out.println(stringBuilder.toString()); stringBuilder.deleteCharAt(stringBuilder.length()-1); // Deletes the character at the specified position



The output is also “abcde” and “abcde”, but the String is much faster than the StringBuilder because of the operation in line 1 and the String STR =”abcde”; It’s exactly the same, so it’s going to be fast, and if I write it in the following form

String str1=”abc”;

String str2=”de”;

String str=str1+str2;

The JVM will continue to create and recycle objects as described above. It’s going to be slow.

public static void main(String[] args) {

long a=new Date().getTime(); String cc=""; int n=10000; for (int i = 0; i < n; i++) { cc+="."+i; } System.out.println(" Time used for String "+(System.currentTimeMillis() -A)/1000.0+"s"); long s1=System.currentTimeMillis(); StringBuilder sb=new StringBuilder(); for (int i = 0; i < n; i++) { sb.append("."+i); } System.out.println(" Time used by StringBuilder "+(System.currentTimeMillis()-s1)/1000.0+"s"); long s2=System.currentTimeMillis(); StringBuffer sbf=new StringBuffer(); for (int i = 0; i < n; i++) { sbf.append("."+i); } System.out.println(" Time used in StringBuffer "+(System.currentTimeMillis()-s2)/1000.0+"s");

}

1.2 Thread-safe In terms of thread-safe, StringBuilder is thread-unsafe, while StringBuffer is thread-safe. If a StringBuffer object is used by multiple threads in the StringBuffer, many methods in the StringBuffer can carry the synchronized keyword and therefore be thread-safe, whereas StringBuilder methods do not have this keyword and therefore cannot be thread-safe. It is possible to do something wrong. So if the operation is multi-threaded then StringBuffer should be used, but in single-threaded cases the faster StringBuilder is recommended. When a thread accesses a synchronized(this) block of code in an object, other threads attempting to access the object are blocked.

1.3 To summarize, String: for a small number of String operations. StringBuilder: Suitable for single-threaded character buffers with a large number of operations. StringBuffer: Suitable for large numbers of operations in character buffers under multiple threads.

A String Pool is a Pool of strings stored in the Java heap memory. We know that String is a special class in Java. We can create String objects using the new operator. We can also create String objects using double quotation marks (” “).

The figure below clearly explains how to maintain a string constant pool in the Java heap memory and how to store it in the heap memory when we create strings in different ways.



The reason for the String constant pool is that strings are immutable in Java, which is an implementation of the String Interning concept. The string constant pool is also an instance of the Flyweight pattern.

String constant pooling helps save a lot of space for the Java runtime, although it takes more time to create strings.

When we create a string using double quotes, we first look in the string constant pool to see if there is a string with the same value, and return a reference to it if there is, otherwise it creates a new string in the pool, and then returns a reference to the new string.

If we use the new operator to create a String, we force the String class to create a new String in the heap space. We can use the intern() method to either put it into the string constant pool or to find a string object with the same value from the string constant pool and return its reference

Here is the implementation of the string constant pool in the figure above:

package cn.gavin.basic; public class StringTest { public static void main(String[] args) { // String s0 = "hello"; // String s1 = "hello"; // String s2 = "he" + "llo"; // System.out.println( s0 == s1 ); // true // System.out.println( s0 == s2 ); // true // System.out.println( s0.equals(s1) ); // true System.out.println("-----------------------"); String s1 = "Cat"; String s2 = "Cat"; String s3 = new String("Cat"); String s4 = new String("Cat"); String s4 = new String("Cat"); String s4 = new String("Cat"); // create a String s5= "Ca"; String s6= s5+"t"; String s7= "Ca"+"t"; System.out.println("s1 == s2 :"+(s1==s2)); System.out.println("s1 == s3 :"+(s1==s3)); System.out.println("s3 == s4 :"+(s3==s4)); System.out.println("s1 == s6 :"+(s1==s6)); System.out.println("s1 == s7 :"+(s1==s7)); System.out.println("-----------------------"); Println ("equals s1-s2 :"+s1.equals(s2)); println("equals s1-s2 :"+s1.equals(s2)); System.out.println("equals s1-s3 :"+s1.equals(s3)); System.out.println("equals s3-s4 :"+s3.equals(s4)); System.out.println("equals s1-s6 :"+s1.equals(s6)); System.out.println("equals s1-s7 :"+s1.equals(s7)); }}

The output of the above program is s1 == s2 :true s1 == s3 :false s3 == s4 :false s1 == s6 :false s1 == s7 :true

equals s1-s2 :true

equals s1-s3 :true

equals s3-s4 :true

equals s1-s6 :true

equals s1-s7 :true

Sometimes in a Java interview, you’ll be asked about the string constant pool. For example, how many String objects are created in the following statement: String STR = new String(“Cat”); In the above statement, it is possible to create 1 or 2 string objects. If there is already a string “Cat” in the pool, then only one string “STR” will be created in the pool. If the string literal “Cat” is not in the pool, it will be created first in the pool and then in the heap space, so a total of two string objects will be created.

2.3 String constant pool Simple understanding of string allocation, like other object allocation, costs a lot of time and space. In order to improve performance and reduce memory overhead, the JVM has made some optimizations when instantiating string constants. To reduce the number of strings created in the JVM, the string class maintains a string pool that the JVM examines first whenever code creates string constants. If the string already exists in the pool, the instance reference in the pool is returned. If the string is not in the pool, a string is instantiated and placed in the pool. Java is able to do this optimization because strings are immutable and can be shared without worrying about data conflicts.

2.4 What is the Java String Constant Pool? Why do we have this constant pool? 1. The pool of strings stored in the Java heap memory. 2


Someone will ask A question: String A = “ABC”; String B = new String(“ABC”); What’s the difference?

When a program uses a string value for the first time,Java will use the constant pool to cache the string value. If the program uses the string value again,Java will use the string value that exists in the constant pool

By default, comparing reference types also compares equals(). Note that the String class overwrites the equals() method to compare the same contents.

Constant pool: Data that is determined at compile time and stored in a compiled.class file. This includes classes, methods, constants in interfaces, and direct string values

String s0 = “hello”;

String s1 = “hello”;

String s2 = “he” + “llo”;

System.out.println( s0 == s1 ); // true

System.out.println( s0 == s2 ); // true

System.out.println( s0.equals(s1) ); // true

(a) equals(b) equals(); (b) equals() equals(); They are all equal, because their addresses are all the same, so there is only one part of the constant pool where the addresses are all the same;

String B = new String(“ABC”); 1 Construct a String in memory and assign a reference to the newly constructed String to STR. (a) {” “==” “; (a) {” “==” “; (b) {” “=” “; (b) As for equals,String overrides the equals() method to determine if the values are equal.