The difference between StringBuffer and StringBuilder classes in Java

To declare a variable of type string in Java, it must be modified with the String keyword, but the variable modified with the String keyword cannot be changed. First of all, String is modified by final, and its length is immutable. Even if the concat method of String is called, it will splicing the strings together and re-create an object, and assign the value of the spliced ​​String to the newly created object. . So what if you want to change its length and content without changing its memory address? At this time, we will use the StringBuffer and StringBuilder classes, and now compare the differences between the two.

Very simple two:

1. StringBuffer is thread-safe, StringBuilder is not thread-safe (cannot access synchronously), if thread safety is required in the program, only StringBuffer can be used;

2. Although StringBuilder is not thread safe, it is faster than StringBuffer. If the program requires thread safety, then we will choose StringBuilder without hesitation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325869156&siteId=291194637
Recommended