×

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java?

Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings.

In Java, strings are objects that represent a sequence of characters. They can be produced with either the String Literal or the NEW keyword. Strings in Java are immutable and stored in the UTF-16 encoding. When a new String is formed, it searches the JVM string pool for a String with the same value. If the value is the same, the reference is returned; otherwise, a String object is constructed and placed in the String pool.

To concatenate two strings, String uses the + operator, and this is done internally using the StringBuffer.

Creating String:

The normal way to create a string in Java is to simply write:-

String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way to create a string is :-

String s = new String (“Hello World”);

Difference between String Buffer and String Builder

String Buffer and String Builder are two types of classes that can be used to manipulate strings. These are mutable objects that provide String manipulation operations such as sub string(), insert(), append(), and delete().

Following are the primary distinctions between StringBuffer and StringBuilder:

                  StringBuffer                 StringBuilder  
When two or more threads are operating on the same String, StringBuffer is used.StringBuilder is only used in a single-threaded atmosphere.
StringBuffer has operations that are thread-safe and synchronizedStringBuilder operations are not thread-safe and are not also synchronized.
When compared to StringBuilder, the performance of StringBuffer is slower.When compared to StringBuffer, StringBuilder performs faster.
Syntax: StringBuffer var = new StringBuffer(str);Syntax: StringBuilder var = new StringBuilder(str);

String vs StringBuilder vs StringBuffer in Java

The following two arguments determine the distinctions between String, StringBuffer, and StringBuilder:

  • Mutability
  • Performance

Mutability

When we compare the phrases above on the mutability factor, we get the following. Strings are immutable, although StringBuffer and StringBuilder are mutable, as previously mentioned. When using the String class, Strings cannot be altered; however, when using the StringBuffer and StringBuilder classes, Strings can change.

Example:

public static void StrConcat(String str1) 
    {    str1 = str1 + "World"; } 
    public static void StrBufConcat(StringBuffer str2) 
    { public class example {


        str2.append("World"); 
    } 
    public static void StrBuildConcat(StringBuilder str3) { 
        str3.append("World"); 
    } 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:

The final string is – Hello!
The final string is – Hello! World
The final string is – Hello! World

StrConcat, StrBufConcat, and StrBuildConcat are the three functions in the code above.

I gave a string -> "Hello!" to the first function, and then used the + operator to perform concatenation [str1 = str1 + "World"]. If you look at the output, you'll notice that the String provided to main() hasn't changed because the String is immutable. Because str1 in main() refers to "World," while str1 in StrConcat() refers to a different object, this is the case.

However, the result of the other two functions, StrBufConcat and StrBuildConcat, is identical since these objects are changeable. I used the add() function to concatenate the Strings in the second and third functions.

Performance

Due to the lack of synchronization, StringBuffer is slower than StringBuilder. This is due to the fact that no additional overhead is required and the procedure is not slowed.

ParameterStringStringBufferStringBuilder
StorageString PoolIt has HeapIt also has a Heap
MutabilityImmutable(unchangeable)Mutable(changeable)Mutable(changeable)
Thread SafeA string is not used in a threaded environmentStringBuffer is used in a multi-threaded environmentStringBuilder is used in a single-threaded environment
PerformanceStrings are slowStringBuffer is slower than StringBuilder but faster than StringStringBuilder is faster than StringBuffer
SyntaxString var =“Hello”;  String var=new String(“Hello”);  StringBuffer var = new StringBuffer("Hello");StringBuilder var = new StringBuilder("Hello");

Related Topics

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.