68 Views

What is the difference between String, StringBuffer and StringBuilder?


Diptangsu Goswami 17th Dec, 2018
Answer (1)
Debosmitha Bhattacharyya Student Expert 17th Dec, 2018

Hello Diptangsu,

Mutability Difference:

A string is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.

Thread-Safety Difference:

The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Situations:

If your string is not going to change use a String class because a String object is immutable.

If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.

If your string can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.

Good luck!

Related Questions

Amity University, Noida Law A...
Apply
700+ Campus placements at top national and global law firms, corporates, and judiciaries
UPES Integrated LLB Admission...
Apply
Ranked #28 amongst Institutions in India by NIRF | Ranked #1 in India for Academic Reputation by QS University Rankings | 16.6 LPA Highest CTC
Great Lakes PGPM & PGDM 2025
Apply
Admissions Open | Globally Recognized by AACSB (US) & AMBA (UK) | 17.3 LPA Avg. CTC for PGPM 2024 | Extended Application Deadline: 10th Jan 2024
Amity University Noida B.Tech...
Apply
Among Top 30 National Universities for Engineering (NIRF 2024)
ISBR Business School PGDM Adm...
Apply
250+ Companies | Highest CTC 16 LPA | Average CTC 8 LPA | Ranked as Platinum Institute by AICTE for 6 years in a row | Awarded Best Business School...
Chandigarh University Admissi...
Apply
Ranked #1 Among all Private Indian Universities in QS Asia Rankings 2025 | Scholarships worth 210 CR
View All Application Forms

Download the Careers360 App on your Android phone

Regular exam updates, QnA, Predictors, College Applications & E-books now on your Mobile

150M+ Students
30,000+ Colleges
500+ Exams
1500+ E-books