Difference between string and stringbuffer

Source: Internet
Author: User

String is a non-variability class, which is characterized by fixed state (there is no method to modify the object). During the lifecycle of the object, its value remains unchanged (it is thread-safe), which is easier to design, implement, and use, not prone to errors, and more secure. 
 
Because the string class supports non-variability, when TMP + = "X" is executed, another object is actually created, the object originally pointed to by TMP becomes garbage (when it has no other references). In this way, a loop will generate n multiple objects, which can be like a waste of memory,

 

String and stringbuffer are both finall classes. The objects they generate are immutable In the heap, and they are implemented by the attribute char array internally,

 

So why can stringbuffer append strings to objects? Haha, because the char array in string is finall, that is, a constant, it cannot be changed, and stringbuffer inherits from the abstract class abstractstringbuilder. Its internal implementation relies on its parent class, the char array in abstractstringbuilder is a variable and can be appended with APPEND.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.