×

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 String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? 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...

4 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.