Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

Difference between String, StringBuffer and StringBuilder in Java – Example attached

Difference between String, StringBuffer and StringBuilder in Java - Comparison and Example attached

In this Java tutorial we will go over difference between Java String, StringBuffer and StringBuilder.

Let’s get started:

String:

The String class represents character strings. All string literals in Java programs, such as “crunchify”, are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created.

StringBuffer:

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.

At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads.

StringBuilder:

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.

This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case).

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Let’s compare all below characteristic of String, StringBuffer and StringBuilder.

String StringBuffer StringBuilder
Thread safe? Yes Yes No
Synchronized? Yes Yes No
Modifiable? No (immutable) Yes (mutable) Yes (mutable)
Storage String Pool Heap Heap
Performance Slow Fast Faster

Java code:

  • Create class: CrunchifyStringVsStringBufferVsStringBuilder.java
  • Put below code into it
  • Save file

In this tutorial, we are adding adding, appending string total 199999 times.

package crunchify.com.tutorial;

/**
 * @author Crunchify.com
 * Program: Difference between String, StringBuffer and StringBuilder in Java - Example attached
 */

public class CrunchifyStringVsStringBufferVsStringBuilder {

    public static void main(String[] args) {

        // String: The String class represents character strings. All string literals
        // in Java programs, such as "abc", are implemented as instances of this class.
        // Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings.
        // Because String objects are immutable they can be shared.
        String crunchifyString = "";
        long crunchifyBefore = System.currentTimeMillis();
        for (int i = 0; i < 199999; i++) {
            crunchifyString = crunchifyString + "crunchify.com";
        }

        long crunchifyAfter = (System.currentTimeMillis());
        crunchifyPrint("Task Completion Time for String: " + (crunchifyAfter - crunchifyBefore));

        // StringBuffer: A thread-safe, mutable sequence of characters. A string buffer is like a String,
        // but can be modified. At any point in time it contains some particular sequence of characters, but the length
        // and content of the sequence can be changed through certain method calls.
        //
        // String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all
        // the operations on any particular instance behave as if they occur in some serial order that is consistent with the order
        // of the method calls made by each of the individual threads involved.
        //
        // The principal operations on a StringBuffer are the append and insert methods,
        // which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends
        // or inserts the characters of that string to the string buffer.
        // The append method always adds these characters at the end of the buffer;
        // the insert method adds the characters at a specified point.

        crunchifyBefore = System.currentTimeMillis();
        StringBuffer crunchifyStringBuffer = new StringBuffer();
        for (int i = 0; i < 199999; i++) {
            crunchifyStringBuffer.append("crunchify.com");
        }

        crunchifyAfter = (System.currentTimeMillis());
        crunchifyPrint("Task Completion Time for StringBuffer: " + (crunchifyAfter - crunchifyBefore));

        // StringBuilder: A mutable sequence of characters.
        // This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
        // This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread
        // (as is generally the case). Where possible,
        // it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
        //
        // The principal operations on a StringBuilder are the append and insert methods,
        // which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends
        // or inserts the characters of that string to the string builder.
        // The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

        crunchifyBefore = System.currentTimeMillis();
        StringBuilder crunchifyStringBuilder;
        crunchifyStringBuilder = new StringBuilder();

        for (int i = 0; i < 199999; i++) {
            crunchifyStringBuilder.append("crunchify.com");
        }
        // OR using repeat().
        // crunchifyStringBuilder.append("crunchify.com".repeat(199999));
        // repeat(): Returns a string whose value is the concatenation of this string repeated count times.

        crunchifyAfter = (System.currentTimeMillis());
        crunchifyPrint("Task Completion Time for StringBuilder: " + (crunchifyAfter - crunchifyBefore));

    }

    private static void crunchifyPrint(String s) {
        System.out.println(s);
    }
}

IntelliJ IDEA Console Result:

Run above program as a Java Application in IntelliJ IDEA or in Eclipse Console and you will result as below.

/Users/app/app/Installation/jdk-17.0.2.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50109:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath :/Users/app/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.32/log4j-over-slf4j-1.7.32.jar crunchify.com.tutorial.CrunchifyStringVsStringBuffer

Task Completion Time for String: 19648
Task Completion Time for StringBuffer: 7
Task Completion Time for StringBuilder: 3

Process finished with exit code 0

Let me know if you face any issue running above program or have any question between String, StringBuffer and StringBuilder.

The post Difference between String, StringBuffer and StringBuilder in Java – Example attached appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires