Home > Java > Javagetting Started > The difference between String, StringBuffer and StringBuilder in java

The difference between String, StringBuffer and StringBuilder in java

王林
Release: 2019-11-29 13:54:55
forward
1895 people have browsed it

The difference between String, StringBuffer and StringBuilder in java

The differences are as follows:

1) Once the content of the String class is declared, it cannot be changed. What changes is only its memory pointer, while the object content of the StringBuffer class is Can be changed.

2) For StringBuffer, object instantiation cannot be completed directly through assignment like String, but must be completed through the constructor method.

3) StringBuffer does not generate new objects when processing strings, and is better than the string class in terms of memory usage. Therefore, in actual use, if you often need to modify a string, such as insertion, deletion and other operations, it is more suitable to use StringBuffer.

Online teaching video sharing: java video

Example: String object cannot be modified means that the object itself cannot be modified, not that the reference cannot be modified.

String a = “你好”;
Copy after login

This line of code means to declare a String type reference variable called a, create a String object in memory (with a value of "Hello"), and then assign the reference of this object to the variable a.

a = “hello”;
Copy after login

The effect of this line of code is to create another String object (with a value of "hello") in the memory, and then assign the reference of this new object to the variable a, instead of assigning the original string object to the memory. The String object value of "hello" becomes "hello".

4) The biggest difference between StringBuilder and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).

5) StringBuilder has a speed advantage compared to StringBuffer, so it is recommended to use the StringBuilder class in most cases. However, when the application requires thread safety, the StringBuffer class must be used.

If you want to know more java related articles, you can visit: Introduction to java programming

The above is the detailed content of The difference between String, StringBuffer and StringBuilder in java. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template