Java/J2EE and SOA (324 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (323 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What are the differences between String, StringBuffer and StringBuilder?

Published on Sep 11,2019 259 Views
7 / 12 Blog from Java Strings

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

A string is an object which represents a sequence of characters. Strings are one of the most popular classes used while programming in Java by developers. But, since Strings are immutable, Java came up with two utility classes: StringBuilder and StringBuffer to make the String manipulations easy. So in this article, I will brief you on the differences between String, StringBuffer and StringBuilder.

The following will be the topics covered:

What are Strings in Java?

Strings in Java are objects used to represent a sequence of character. They can be either created using the String Literal or by using the NEW keyword. Strings are immutable in Java are represented in the UTF-16 format. When a new String is created, it looks for the String with the same value in the JVM string pool. If it finds a same value, then it returns the reference else it created a String object and places that object in the String pool.

Apart from this, String uses the + operator to concatenate two strings and internally used the StringBuffer to perform this action. If you wish to know more about Strings in Java and its methods, you can refer to the article – Java Strings.

Since Strings are immutable in Java, whenever String manipulations are performed, automatically a new String would be generated by discarding the older one. But, don’t you think, this is cumbersome when we have large applications?

Well, to avoid garbage in heap, Java came up with StringBuffer and StringBuilder. So next in this article let us understand what are StringBuffer and StringBuilder.

What are the differences between StringBuffer and StringBuilder?

StringBuffer and StringBuilder are classes used for String manipulation. These are mutable objects, which provide methods such as substring(), insert(), append(), delete() for String manipulation.

The main differences between StringBuffer and StringBuilder are as follows:

StringBufferStringBuilder
StringBuffer operations are thread-safe and synchronizedStringBuilder operations are not thread-safe are not-synchronized.
StringBuffer is to used when multiple threads are working on the same String StringBuilder is used in a single-threaded environment.
StringBuffer performance is slower when compared to StringBuilderStringBuilder performance is faster when compared to StringBuffer 
Syntax: StringBuffer var = new StringBuffer(str);Syntax: StringBuilder var = new StringBuilder(str);

Next, in this article, let us see the differences between String, StringBuffer and StringBuilder.

String vs StringBuilder vs StringBuffer in Java

The differences between String, StringBuffer, and StringBuilder are based on the following two parameters:

  • Mutability
  • Performance

Let us look into each one of them one by one.

Mutability

Well, when we compare the above terms, on the factor Mutability. Then, as mentioned before, Strings are immutable while StringBuffer and StringBuilder are mutable. So, Strings cannot be changed when you use the String class; whereas Strings can change if you use the StringBuffer and StringBuilder class.

Consider the following code snippet:

package edureka;

public class example {
	
    public static void StrConcat(String str1) 
    { 
        str1 = str1 + "Edureka"; 
    } 
  
    public static void StrBufConcat(StringBuffer str2) 
    { 
        str2.append("Edureka"); 
    } 
  
    public static void StrBuildConcat(StringBuilder str3) 
    { 
        str3.append("Edureka"); 
    } 
  
    public static void main(String[] args) 
    { 
        String str1 = "Hello!"; 
        StrConcat(str1); 
        System.out.println("The final String is - " + str1); 
  
        StringBuffer str2 = new StringBuffer("Hello!"); 
        StrBufConcat(str2); 
        System.out.println("The final String is - " + str2); 
  
        StringBuilder str3 = new StringBuilder("Hello!"); 
        StrBuildConcat(str3);
        System.out.println("The final String is -" + str3); 
    } 
} 

Output:

Output - Differences Between String, StringBuffer and StringBuilder - Edureka

In the above code, I have three functions: StrConcat, StrBufConcat, and StrBuildConcat.

In the first function, I have passed a string -> “Hello!” and then to perform concatenation, I have used the + operator as [str1 = str1 + “Edureka”]. Now, if you observe the output, the String passed in the main() did not change, as String is immutable. This is because str1 in main() references to “Edureka” and str1 in StrConcat() references to a different object.

But, if you look at the other two functions: StrBufConcat, and StrBuildConcat; the output is the same as these objects are mutable. In the second and the third function, I have used the append() function to concatenate the Strings.

Performance

StringBuilder is faster than StringBuffer as it offers no synchronization. This is because no extra overhead needs to be added to the system and also does not slows down the processing.

If I have to summarize the differences between String, StringBuffer and StringBuilder, then refer to the below table:

ParameterStringStringBufferStringBuilder
StorageString PoolHeapHeap
MutabilityImmutableMutableMutable
Thread SafeNot used in a threaded environmentUsed in a multi-threaded environmentUsed in a single-threaded environment
PerformanceSlowSlower than StringBuilder but faster than StringFaster than StringBuffer
SyntaxString var =“Edureka”

String var=new String(“Edureka”);  

StringBuffer var = new StringBuffer("Edureka");StringBuilder var = new StringBuilder("Edureka");

With this, we come to an end to this article. I hope you found this article informative.

Now that you have understood basics of Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this article on “String vs StringBuilder vs StringBuffer in Java” and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.