What are the classes for manipulating strings in java? What are the differences between them?

  Commonly used string manipulation classes in Java are:

  1.String class

  The String class is the most commonly used string class in Java. It is an immutable string, that is, it cannot be modified after it is created.

  2.StringBuilder class

  The StringBuilder class is also a string operation class, but it is variable, that is, the created string object can be modified. StringBuilder is more suitable for string concatenation in programs than String.

  3.StringBuffer class

  The StringBuffer class is similar to the StringBuilder class, and it is also a variable string operation class, but it is thread-safe, that is, multiple threads can access the same StringBuffer object at the same time, so it is safer to use StringBuffer than StringBuilder in a multi-threaded environment.

  The main differences between the three classes are mutability, thread safety, and performance. String is immutable, so when performing operations such as string splicing, each operation will create a new string object, which will take up more memory space and time. However, StringBuilder and StringBuffer are variable and can directly modify existing string objects, so they are more efficient. StringBuilder is faster than StringBuffer, but not thread-safe, so you need to use StringBuffer in a multi-threaded environment.

  In general, if you only perform simple string operations, you can use the String class. If you need to frequently perform operations such as string concatenation, it is recommended to use StringBuilder. If you use it in a multi-threaded environment, you should use StringBuffer.

  Next, we use a piece of code to illustrate:

public class StringDemo {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "world";
        String str3 = str1 + str2; // 会创建一个新的对象
        System.out.println(str3);

        StringBuilder sb1 = new StringBuilder("hello");
        sb1.append("world"); // 不会创建新的对象
        System.out.println(sb1.toString());

        StringBuffer sb2 = new StringBuffer("hello");
        sb2.append("world"); // 不会创建新的对象
        System.out.println(sb2.toString());
    }
}

  The output is:

helloworld
helloworld
helloworld

  It can be seen that using the String class for string splicing will create new objects, but using the StringBuilder and StringBuffer classes will not create new objects.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130280135
Recommended