The Wayback Machine - https://web.archive.org/web/20240906180803/https://www.geeksforgeeks.org/string-vs-stringbuilder-vs-stringbuffer-in-java/
Open In App

String vs StringBuilder vs StringBuffer in Java

Last Updated : 02 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created. Initializing a String is one of the important pillars required as a pre-requisite with deeper understanding.

Comparison between String, StringBuilder, and StringBuffer

Feature

String

StringBuilder

StringBuffer

Introduction

Introduced in JDK 1.0

Introduced in JDK 1.5

Introduced in JDK 1.0

Mutability

Immutable

Mutable

Mutable

Thread Safety

Thread Safe

Not Thread Safe

Thread Safe

Memory Efficiency

High

Efficient

Less Efficient

Performance

High(No-Synchronization)

High(No-Synchronization)

Low(Due to Synchronization)

Usage

This is used when we want immutability.

This is used when Thread safety is not required.

This is used when Thread safety is required.

Now, we will be justifying. Let us do consider the below code with three concatenation functions with three different types of parameters, String, StringBuffer, and StringBuilder. Let us clear out the understanding between them via a single Java program below from which we will be drawing out conclusions from the output generated, to figure out differences between String vs StringBuilder vs StringBuffer in Java.

Example

Java
// Java program to demonstrate difference between
// String, StringBuilder and StringBuffer

// Main class
class GFG {

    // Method 1
    // Concatenates to String
    public static void concat1(String s1)
    {
        s1 = s1 + "forgeeks";
    }

    // Method 2
    // Concatenates to StringBuilder
    public static void concat2(StringBuilder s2)
    {
        s2.append("forgeeks");
    }

    // Method 3
    // Concatenates to StringBuffer
    public static void concat3(StringBuffer s3)
    {
        s3.append("forgeeks");
    }

    // Method 4
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        // String 1
        String s1 = "Geeks";

        // Calling above defined method
        concat1(s1);

        // s1 is not changed
        System.out.println("String: " + s1);

        // String 1
        StringBuilder s2 = new StringBuilder("Geeks");

        // Calling above defined method
        concat2(s2);

        // s2 is changed
        System.out.println("StringBuilder: " + s2);

        // String 3
        StringBuffer s3 = new StringBuffer("Geeks");

        // Calling above defined method
        concat3(s3);

        // s3 is changed
        System.out.println("StringBuffer: " + s3);
    }
}

Output
String: Geeks
StringBuilder: Geeksforgeeks
StringBuffer: Geeksforgeeks

 Output explanation:

  • Concat1: In this method, we pass a string “Geeks” and perform “s1 = s1 + ”forgeeks”. The string passed from main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and s1 in concat1() stores reference of the new string. References s1 in main() and cocat1() refer to different strings.
  • Concat2: In this method, we pass a string “Geeks” and perform “s2.append(“forgeeks”)” which changes the actual value of the string (in main) to “Geeksforgeeks”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
  • Concat3: StringBuilder is similar and can be compatible at all places to StringBuffer except for the key difference of thread safety. StringBuffer is thread-safe while StringBuilder does not guarantee thread safety which means synchronized methods are present in StringBuffer making control of one thread access at a time while it is not seen in StringBuilder, hence thread-unsafe.
     

Note: Geeks now you must be wondering when to use which one, do refer below as follows:

  • If a string is going to remain constant throughout the program, then use the String class object because a String object is immutable.
  • If a string can change (for 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 a string can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous, so you have thread-safety.
  • If you don’t want thread-safety than you can also go with StringBuilder class as it is not synchronized.

Conversion between types of strings in Java

Sometimes there is a need for converting a string object of different classes like String, StringBuffer, StringBuilder to one another. Below are some techniques to do the same. Let us do cover all use cases s follows:

  1. From String to StringBuffer and StringBuilder
  2. From StringBuffer and StringBuilder to String
  3. From StringBuffer to StringBuilder or vice-versa

Case 1: From String to StringBuffer and StringBuilder 

This one is an easy way out as we can directly pass the String class object to StringBuffer and StringBuilder class constructors. As the String class is immutable in java, so for editing a string, we can perform the same by converting it to StringBuffer or StringBuilder class objects.

Example  

Java
// Java program to demonstrate conversion from
// String to StringBuffer and StringBuilder

// Main class
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "Geeks";

        // Converting String object to StringBuffer object
        // by
        // creating object of StringBuffer class
        StringBuffer sbr = new StringBuffer(str);

        // Reversing the string
        sbr.reverse();

        // Printing the reversed string
        System.out.println(sbr);

        // Converting String object to StringBuilder object
        StringBuilder sbl = new StringBuilder(str);

        // Adding it to string using append() method
        sbl.append("ForGeeks");

        // Print and display the above appended string
        System.out.println(sbl);
    }
}

Output
skeeG
GeeksForGeeks

Case 2: From StringBuffer and StringBuilder to String 

This conversion can be performed using toString() method which is overridden in both StringBuffer and StringBuilder classes. 
Below is the java program to demonstrate the same. Note that while we use toString() method, a new String object(in Heap area) is allocated and initialized to the character sequence currently represented by the StringBuffer object, which means the subsequent changes to the StringBuffer object do not affect the contents of the String object. 

Example

Java
// Java Program to Demonstrate Conversion from
// String to StringBuffer and StringBuilder

// Main class
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating objects of StringBuffer class
        StringBuffer sbr = new StringBuffer("Geeks");
        StringBuilder sbdr = new StringBuilder("Hello");

        // Converting StringBuffer object to String
        // using toString() method
        String str = sbr.toString();

        // Printing the above string
        System.out.println(
            "StringBuffer object to String : ");
        System.out.println(str);

        // Converting StringBuilder object to String
        String str1 = sbdr.toString();

        // Printing the above string
        System.out.println(
            "StringBuilder object to String : ");
        System.out.println(str1);

        // Changing StringBuffer object sbr
        // but String object(str) doesn't change
        sbr.append("ForGeeks");

        // Printing the above two strings on console
        System.out.println(sbr);
        System.out.println(str);
    }
}

Output
StringBuffer object to String : 
Geeks
StringBuilder object to String : 
Hello
GeeksForGeeks
Geeks

Case 3: From StringBuffer to StringBuilder or vice-versa

This conversion is tricky. There is no direct way to convert the same. In this case, We can use a String class object. We first convert the StringBuffer/StringBuilder object to String using toString() method and then from String to StringBuilder/StringBuffer using constructors.

Example

Java
// Java program to Demonstrate conversion from
// String to StringBuffer and StringBuilder

// Main class
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of StringBuffer class and
        // passing our input string to it
        StringBuffer sbr = new StringBuffer("Geeks");

        // Storing value StringBuffer object in String and
        // henceforth converting StringBuffer object to
        // StringBuilder class
        String str = sbr.toString();
        StringBuilder sbl = new StringBuilder(str);

        // Printing the StringBuilder object on console
        System.out.println(sbl);
    }
}

Output
Geeks

From the above three use-cases we can conclude out below pointers: 

  • Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable.
  • StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for the single-threaded program. If thread safety is needed, then StringBuffer is used.

Related Article: Reverse a String in Java (5 Different Ways)



Previous Article
Next Article

Similar Reads

Difference Between StringBuffer and StringBuilder in Java
Strings in Java are the objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. However, java provides multiple classes through which strings can be used. Two such classes are StringBuffer and StringBuilder.
4 min read
equals() on String and StringBuffer objects in Java
Consider the following codes in java: Java Code // This program prints false class GFG { public static void main(String[] args) { StringBuffer sb1 = new StringBuffer("GFG"); StringBuffer sb2 = new StringBuffer("GFG"); System.out.println(sb1.equals(sb2)); } } Output: false Java Code // This program prints true class GFG { public
2 min read
Matcher appendReplacement(StringBuffer, String) method in Java with Examples
The appendReplacement(StringBuffer, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuffer buffer, String stringToBeReplaced) Parameters: This method takes two parameters: buffer: w
3 min read
Sorting collection of String and StringBuffer in Java
Sorting a collection of objects can be done in two ways: By implementing Comparable (Natural Order) e.g. Strings are sorted ASCIIbetically. meaning B comes before A and 10 is before 2.By implementing Comparator (Custom order) and it can be in any order.Using Collections.sort() method of Collections utility class. Read more about Comparable and Comp
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and replace it with the matched pattern in the matcher string. Syntax: public Matcher appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters: This method takes two parameters: builde
3 min read
StringBuffer insert() in Java
The StringBuffer.insert() method inserts the string representation of given data type at given position in a StringBuffer. Syntax: str.insert(int position, char x); str.insert(int position, boolean x); str.insert(int position, char[] x); str.insert(int position, float x); str.insert(int position, double x); str.insert(int position, long x); str.ins
4 min read
StringBuffer deleteCharAt() Method in Java with Examples
The Java.lang.StringBuffer.deleteCharAt() is a built-in Java method which removes the char at the specified position in this sequence. So that the sequence is reduced by 1 char. Syntax: public StringBuffer deleteCharAt(int indexpoint) Parameters : The method accepts a single parameter indexpoint of integer type which refers to the index of the char
2 min read
StringBuffer appendCodePoint() Method in Java with Examples
appendCodePoint() method of StringBuffer class appends the string representation of the codePoint argument to this sequence for which we require pre-requisite knowledge of ASCII table as then only we will be able to perceive output why the specific literal is being appended as there is already an integer value been assigned. --> appendCodePoint(
3 min read
StringBuffer delete() Method in Java with Examples
The java.lang.StringBuffer.delete() is an inbuilt method in Java which is used to remove or delete the characters in a substring of this sequence. The substring starts at a specified index start_point and extends to the character at the index end_point. Syntax : public StringBuffer delete(int start_point, int end_point) Parameters : The method acce
3 min read
StringBuffer replace() Method in Java with Examples
The StringBuffer.replace() is the inbuilt method which is used to replace the characters in a substring of this sequence with the characters in the specified String. Here simply the characters in the substring are removed and other char is inserted at the start.Syntax : public StringBuffer replace(int first, int last, String st) Parameters : The me
2 min read
StringBuffer reverse() Method in Java with Examples
The Java.lang.StringBuffer.reverse() is an inbuilt method that is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. Syntax: public StringBuffer reverse() Parameters: NA Return Value: The method returns the StringBuffer after reversing the characters. Examples
2 min read
StringBuffer append() Method in Java with Examples
Pre-requisite: StringBuffer class in Java The java.lang.StringBuffer.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used: StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an inbuilt method in Java which is used t
13 min read
StringBuffer setLength() in Java with Examples
The setLength(int newLength) method of StringBuffer class is the inbuilt method used to set the length of the character sequence equal to newLength. If the newLength passed as argument is less than the old length, the old length is changed to the newLength. If the newLength passed as argument is greater than or equal to the old length, null charact
2 min read
StringBuffer subSequence() in Java with Examples
The subSequence(int start, int end) method of StringBuffer class is the inbuilt method used to return a subsequence of characters lie between index start and end-1 of this sequence. The subsequence starts with the char value at the index start and ends with the char value at (end-1). The length of the returned subsequence is end-start. So if start
3 min read
StringBuffer codePointCount() method in Java with Examples
The codePointCount() method of StringBuffer class is used to return the number of Unicode code points in the specified range of beginIndex to endIndex of String contained by StringBuffer. This method takes beginIndex and endIndex as a parameter where beginIndex is the index of the first character of the text range and endIndex is index after the la
3 min read
StringBuffer codePointBefore() method in Java with Examples
The codePointBefore() method of StringBuffer class is a method used to take an index as a parameter and returns the “Unicode number” of the character present before that index. The value of index must lie between 0 to length-1. If the char value at (index – 1) is in the low-surrogate range, char at (index – 2) is not negative with value is in the h
2 min read
StringBuffer trimToSize() method in Java with Examples
The trimToSize() method of StringBuffer class is the inbuilt method used to trims the capacity used for the character sequence of StringBuffer object. If the buffer used by StringBuffer object is larger than necessary to hold its current sequence of characters, then this method is called to resize the StringBuffer object for converting this object
2 min read
StringBuffer toString() method in Java with Examples
The toString() method of StringBuffer class is the inbuilt method used to returns a string representing the data contained by StringBuffer Object. A new String object is created and initialized to get the character sequence from this StringBuffer object and then String is returned by toString(). Subsequent changes to this sequence contained by Obje
2 min read
StringBuffer codePointAt() method in Java with Examples
The codePointAt() method of StringBuffer class returns a character Unicode point at that index in sequence contained by StringBuffer. This method returns the “Unicodenumber” of the character at that index. Value of index must be lie between 0 to length-1. If the char value present at the given index lies in the high-surrogate range, the following i
2 min read
StringBuffer ensureCapacity() method in Java with Examples
The ensureCapacity() method of StringBuffer class ensures the capacity to at least equal to the specified minimumCapacity. If the current capacity of StringBuffer < the argument minimumCapacity, then a new internal array is allocated with greater capacity.If the minimumCapacity argument > twice the old capacity, plus 2 then new capacity is eq
2 min read
StringBuffer offsetByCodePoints() method in Java with Examples
The offsetByCodePoints() method of StringBuffer class returns the index within this String contained by StringBuffer that is offset from the index passed as parameter by codePointOffset code points. Unpaired surrogates lies between index and codePointOffset count as one code point each. Syntax: public int offsetByCodePoints(int index, int codePoint
2 min read
StringBuffer setCharAt() method in Java with Examples
The setCharAt() method of StringBuffer class sets the character at the position index to character which is the value passed as parameter to method. This method returns a new sequence which is identical to old sequence only difference is a new character ch is present at position index in new sequence. The index argument must be greater than or equa
2 min read
StringBuffer getChars() method in Java with Examples
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of StringBuffer class copies the characters starting at the index:srcBegin to index:srcEnd-1 from actual sequence into an array of char passed as parameter to function. The characters are copied into the array of char dst[] starting at index:dstBegin and ending at index:dstbegi
3 min read
StringBuffer indexOf() method in Java with Examples
In StringBuffer class, there are two types of indexOf() method depending upon the parameters passed to it. indexOf(String str) The indexOf(String str) method of StringBuffer class is used to return the index of the String for first occurrence of passed substring as parameter from the sequence contained by this object. If substring str is not presen
4 min read
StringBuffer substring() method in Java with Examples
In StringBuffer class, there are two types of substring method depending upon the parameters passed to it. substring(int start) The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character f
3 min read
StringBuffer lastIndexOf() method in Java with Examples
In StringBuffer class, there are two types of lastIndexOf() method depending upon the parameters passed to it. lastIndexOf(String str) The lastIndexOf(String str) method of StringBuffer class is the inbuilt method used to return the index within the String for last occurrence of passed substring as parameter. The last occurrence of the empty string
4 min read
Matcher appendTail(StringBuffer) method in Java with Examples
The appendTail(StringBuffer) method of Matcher Class behaves as a append-and-replace method. This method reads the input string and appends it to the given StringBuffer at the tail position. Syntax: public StringBuffer appendTail(StringBuffer buffer) Parameters: This method takes a parameter buffer which is the StringBuffer that stores the target s
2 min read
A Java Random and StringBuffer Puzzle
Predict the output of the program import java.util.Random; public class GFG { private static Random rd = new Random(); public static void main(String[] args) { StringBuffer word = null; switch(rd.nextInt(2)) { case 1: word = new StringBuffer('P'); case 2: word = new StringBuffer('G'); default: word = new StringBuffer('M'); } word.append('a'); word.
2 min read
StringBuffer class in Java
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alternative to the immutable String class, allowing you to modify the contents of a string without creating a new object every time. Here are some important features and methods of the StringBuffer class:StringBuffer objects are mutable, meaning that yo
13 min read
StringBuilder Class in Java with Examples
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer class, as both of them
6 min read