EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials Top Differences Tutorial String vs StringBuffer
 

String vs StringBuffer

Priya Pedamkar
Article byPriya Pedamkar

Updated March 24, 2023

String vs StringBuffer

 

 

Difference Between String vs StringBuffer

In JAVA, both String and StringBuffer classes are used to work with strings and are present in java.lang package. The major difference between String vs StringBuffer is:

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

A string is Immutable: Once you create an object of String, you cannot change it. Every modification on the string creates a new String object and discards the older one, which creates lots of temporary garbage in a heap.

StringBuffer is Mutable: Object of StringBuffer is mutable, i.e. performing modifications on the string using StringBuffer will not create new objects in the memory, but it will update the content of string in an existing object.

Head to Head Comparison Between String vs StringBuffer (Infographics)

Below are the top 7 differences between String vs StringBuffer:String-vs-StringBuffer-info

Key Differences Between String vs StringBuffer

let us discuss some of the major Difference Between String vs StringBuffer:

  1. If we perform any operations on a string using the String class, it results in creating an entire string in the memory repeatedly, whereas StringBuffer occupies some buffer space and modifies string value in that buffer space in the memory.
  • Internal Working of String Class
String str = new String("Everything ");
Str.concat("is ");
Str.concat("learnable");

Internal Working of String Class

  • Internal Working of StringBuffer Class
StringBuffer sb = new StringBuffer("Everything ");
sb.append("is ");
sb.append("learnable");

Internal Working of StringBuffer Class

2. In the case of heavy string manipulations and many string concatenations, StringBuffer provides better performance than String.

Code:

import java.util.*;
public class Main
{
public static String StringConcat()
{
String str = "Hello";
for (int i = 0; i < 1000; i++)
{
str = str + "World";
}
return str;
}
public static String StringBufferConcat()
{
StringBuffer stringBuffer = new StringBuffer("Hello");
for (int i = 0; i < 1000; i++)
{
stringBuffer.append("World");
}
return stringBuffer.toString();
}
public static void main(String args[])
{
long time= System.currentTimeMillis();
StringConcat();
System.out.println("Time taken for String Concatenation: " + (System.currentTimeMillis()
- time) + "ms");
time = System.currentTimeMillis();
StringBufferConcat();
System.out.println("Time taken for StringBuffer Concatenation: " + (System.currentTimeMillis()
- time) + "ms");
}
}

Output:

String vs StringBuffer eg1

3. As the String class creates lots of string garbage in the memory after performing any operation on a string, it requires more memory as compared to StringBuffer.

4. If multiple string concatenations or heavy operations are required to perform on the string, StringBuffer should be used. If the string’s content is not going to change throughout the program, then the String class should be used to work with strings in a thread-safe manner.

5. If a very less number of string concatenations are required, then the String class is efficient and works faster than StringBuffer because adding characters in buffer space and then converting the whole content to string again creates overhead for StringBuffer. Thus, in this case, StringBuffer works slower as compared to copy by value nature of String class.

6. String class overrides equals() and hashCode() methods of the Object class whereas StringBuffer does not override equals() and hashCode() methods of Object class.

Code:

import java.util.*;
public class Main
{
public static void main(String args[])
{
System.out.println("Performing hash code test on String:");
String str = "Everything";
System.out.println("Hash code value of 'Everything': " + str.hashCode());
str = str + "is";
System.out.println("Hash code value of 'is': " + str.hashCode());
str = str + "learnable";
System.out.println("Hash code value of 'learnable': " + str.hashCode());
System.out.println("");
System.out.println("Performing hash code test on StringBuffer:");
StringBuffer stringBuffer = new StringBuffer("Everything");
System.out.println("Hash code value of 'Everything': " + stringBuffer.hashCode());
stringBuffer.append("is");
System.out.println("Hash code value of 'is': " + stringBuffer.hashCode());
stringBuffer.append("learnable");
System.out.println("Hash code value of 'learnable': " + stringBuffer.hashCode());
}
}

Output:

String vs StringBuffer 2

In the above output, we can see that String returns different hash code values for different strings, whereas StringBuffer returns the same hash code values for all strings. This proves that the String class overrides the hashCode() method of the Object class.

7. String literals are stored in a constant string pool, whereas StringBuffer objects are stored in a heap.

8. The String class’s object is of fixed length and read-only in nature, whereas the length of an object of StringBuffer can be increased when required and dynamic in nature.

9. String class supports interning, i.e. strings with the same content share the same memory location, whereas StringBuffer does not support interning.

Code:

import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); //returns true
String str3 = str1.intern();
System.out.println(str1 == str3); //returns true
}
}

Output:

String vs StringBuffer 3

10. We can convert the String object to the StringBuffer object by passing the String object to the StringBuffer class constructor, whereas to convert the StringBuffer object to the String object, we need to call the toString() method.

Example:

String str = "abc";
StringBuffer stringBuffer = new StringBuffer(str);
StringBuffer stringBuffer = new StringBuffer("abc");
String str = stringBuffer.toString();

Comparison Table of String and StringBuffer

Let’s us see the topmost comparison between String vs StringBuffer:

Parameter String StringBuffer
Modifiable The object of the String class isn’t modifiable. The object of the StringBuffer class is modifiable.
Performance Slower than StringBuffer class for a large number of string concatenations. Faster than the String class for a large number of string concatenations.
Storage Area String literals are stored in a constant string pool. StringBuffer objects are Stored in a heap.
Memory Requirement It consumes more memory than StringBuffer. It consumes less memory than String.
Behavior of object An object of String class is of fixed length, i.e. read-only in nature. The length of the StringBuffer object can be increased when required, i.e. dynamic in nature.
Efficiency Less efficient than StringBuffer in case of concatenating many strings together in a loop. More efficient than String in case of concatenating many strings together in a loop.
Overriding equals() and hashCode() methods String class overrides equals() and hashCode() methods of Object class. StringBuffer does not override equals() and hashCode() methods of Object class.

Conclusion

In JAVA, both String and StringBuffer classes are used to represent a sequence of characters. If the string’s operations do not change its value, then the String class does not create a new object for the string. A new object is created when the value of the string changes.

Recommended Articles

This is a guide to String vs StringBuffer. Here we discuss the String vs StringBuffer key differences with infographics and comparison table. You may also have a look at the following articles to learn more –

  1. C# Interface vs Abstract Class
  2. Typescript interface vs class
  3. Java Interface vs Abstract Class
  4. String vs String C#

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Limited Time Offer! - ENROLL NOW