×

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

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute 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.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 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.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.