search
HomeJavajavaTutorialThe difference between String and StringBuffer in JAVA

The difference between String and StringBuffer can be said to be countless on the Internet, but when I saw this article, I felt that the small examples in it were very representative, so I turned to it and made a summary myself.

There are 3 classes in java that are responsible for character operations.

1.Character operates on a single character, and

2.String operates on a string of characters. Immutable classes.

3.StringBuffer also operates on a string of characters, but it is a variable class.

String:
is an object that is not a primitive type.
is an immutable object. Once it is created, its value cannot be modified.
Any modification to an existing String object is to create a new object and then add the new one. The value is saved in.
String is a final class, that is, it cannot be inherited.

StringBuffer:
is a mutable object. When it is modified, the object will not be re-established like String.
It can only be created through the constructor ,
StringBuffer sb = new StringBuffer();
note: It cannot be paid through the value symbol.
sb = "welcome to here!";//error
After the object is created, memory will be allocated in the memory space, and initially saves a null. When paying value to StringBuffer
, you can use its append method.
sb.append("hello");

StringBuffer is more efficient than String in string connection operations:

String str = new String("welcome to ");
str += "here"; The processing steps of
are actually to create a StringBuffer, let you call append(), and finally
then convert StringBuffer toSting();
like this In this case, String's connection operation requires some additional operations than StringBuffer, but of course the efficiency will be compromised.

And since the String object is an immutable object, a new object will be re-established every time Sting is operated to save the new value.
This way The original object is useless and will be garbage collected. This will also affect performance.

Look at the following code:
Added 26 English letters 5000 times,

1.       String tempstr = "abcdefghijklmnopqrstuvwxyz" ;
2. int times = 5000;
3. long lstart1 = System.currentTimeMillis();
4. String str = "";
5. for (int i = 0; i 6 .          str += tempstr;
7.                        long lend1 = System.currentTimeMillis(); The computer is not a supercomputer, and the result obtained may not be the same every time, usually around 46687.
That’s 46 seconds.
Let’s take a look at the following code again

1.       String tempstr = "abcdefghijklmnopqrstuvwxyz";
2.      int times = 5000;
3.         long lstart2 = System.currentTimeMillis();

4.       StringBuffer sb = new StringBuffer();

5. for (int i = 0; i 6. sb.append(tempstr);
7. long lend2 = System.currentTimeMillis();
9. long time2 = ( lend2 - lstart2);
10. System.out.println(time2);
The result is 16 and sometimes 0
So the conclusion is obvious, StringBuffer is almost tens of thousands times faster than String. Of course this data is not very accurate. Because when the number of cycles is 100,000, the difference is even greater. If you don’t believe me, try it.



According to the above:

str += "here";

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

then StringBuffer toSting();

so str += "here"; can be equivalent to


StringBuffer sb = new StringBuffer(str);

sb.append("here");

str = sb.toString();

So the above directly uses "+" The code to connect String can be basically equivalent to the following code

1.       String tempstr = "abcdefghijklmnopqrstuvwxyz";
2.       int times = 5000;
3.        long lstart2 = System.currentTimeMillis(); int i = 0; i 6.             StringBuffer sb = new StringBuffer(str); 
7.           sb.append(tempstr); 
8.                 str = sb. long lend2 = System.currentTimeMillis();
11. long time2 = (lend2 - lstart2);
12. System.out.println(time2);
The average execution time is about 46922, which is 46 seconds.



Summary: If you need to frequently modify and connect strings in your program, the performance will be higher using StringBuffer

Statement
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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),