×

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

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.