What is the difference between a string in Java and StringBuffer

Source: Internet
Author: User
Tags garbage collection stringbuffer

The difference between string and stringbuffer, online data can be said to be countless, but see this article, feel inside do small examples are very representative, so turn, and do a little summary of their own.

There are 3 classes in Java that are responsible for the operation of characters:

1.Character is a single character operation.

2.String operation on a string of characters, immutable class.

3.StringBuffer is also an operation on a string of characters, but a mutable class.

String:

Is that the object is not the original type.

is an immutable object, and once created, it cannot modify its value.

The modification of a string object that already exists is to re-create a new object and then save the new value in.

String is the final class, which cannot be inherited.

StringBuffer:

is a mutable object that, when modified, does not re-establish objects like string

It can only be built through constructors,

StringBuffer sb = new StringBuffer ();

Note: You cannot pay the value by paying the value sign.

SB = "Welcome to here!"; /error

After the object is established, the memory space is allocated in memory and a null is initially saved. to StringBuffer

The Append method can be used when the value is paid.

Sb.append ("Hello");

StringBuffer is more efficient in string concatenation operations than string:

String str = new String ("Welcome to");

str = "Here";

The processing step is actually to create a stringbuffer, let Hou call append (), and finally

Then the StringBuffer tosting ();

In this way the string concatenation operation is more than StringBuffer, of course, the efficiency of the discount.

And because a string object is an immutable object, each operation sting a new object to hold the new value.

So the original object is useless, it will be garbage collection. This is also to affect performance.

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.