×

Java String vs StringBuffer

Java String vs StringBuffer

In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes.

String Class

The String class represents character strings. All string literals in Java programs, such as "xyz", 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.

StringBuffer Class

StringBuffer is a thread-safe, mutable sequence of characters. It is the same as a String. The only difference is that it cannot 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

Difference Between String and StringBuffer Class

StringStringBuffer
String is an immutable class.StringBuffer is a mutable class.
Concatenation of string is slow in the String class.Concatenation of string is fast in the StringBuffer class.
Contents of the two strings can be compared using the equals() method, as the String class overrides the equals() method of the Object class.Contents of the two strings cannot be compared using the equals() method, as the StringBuffer class does not override the equals() method of the Object class.

Performance Comparison

The following comparison is based on the basis of the concatenation of string for the String class and the StringBuffer class.

FileName: PerformanceTestExample.java

 // A basic Java program that compares the performance of String and StringBuffer
public class PerformanceTestExample
{ 
// main method
public static void main(String argvs[])
{ 
long sTime = System.currentTimeMillis();
// creating an object of String
String str = new String("Hi "); 
for (int j = 0; j < 10000; j++)
{ 
    // doing the concatenation work
    str += ("Tutorial & Example"); 
}
// displaying the time taken by String
System.out.println("Total Time consumed by the String is: " + (System.currentTimeMillis() - sTime) + "ms"); 
// resetting the start time
sTime = System.currentTimeMillis();
// creating an object of StringBuffer
StringBuffer strBuffer = new StringBuffer("Hi "); 
for (int j = 0; j < 10000; j++)
{ 
    // doing the concatenation work
    strBuffer.append("Tutorial & Example"); 
} 
// displaying the time taken by StringBuffer
System.out.println("Total Time consumed by the StringBuffer is: " + (System.currentTimeMillis() - sTime) + "ms");
} 
}  

Output:

 Total Time consumed by the String is: 349ms
Total Time consumed by the StringBuffer is: 2ms 

Explanation: It is evident that the manipulation of a string in the String class is much slower as compared to the StringBuffer class. The reason behind this is the String class is immutable. Therefore, when a string in the String class is manipulated, the current string is not manipulated at all. Instead of manipulating the current string, memory for a new string is allocated, and a new string is generated. All these memory allocation and generation of the new string take time.

Because StringBuffer class is mutable, no new string is generated when the string manipulation is done. The current string is manipulated to get the desired output. Therefore, the manipulation is faster in the StringBuffer class as compared to the String class.

Hash Code Test for String and StringBuffer

We have learnt that when a string is manipulated in the String class, a new string is generated, and the same is not true for the StringBuffer class. Let’s confirm it with the help of an example.

FileName: HashCodeTestExample.java

 // A basic Java program that performs the hash code test for String and StringBuffer
public class HashCodeTestExample
{ 
// main method
public static void main(String argvs[])
{ 
System.out.println("Performing The Hash Code test for String: \n");
// creating an object of String
String str = new String("Hi "); 
System.out.println("String is: " + str );
// printing the hashcode of the object str
System.out.println("Hashcode of the string object is: " + str.hashCode());
// doing the concatenation work
str += ("Tutorial & Example"); 
System.out.println("\nString is: " + str);
// printing the hashcode of the object str
System.out.println("Hashcode of the String object is: " + str.hashCode()); 
System.out.println("\nPerforming The Hash Code test for the StringBuffer: \n");
// creating an object of StringBuffer
StringBuffer strBuffer = new StringBuffer("Hi "); 
System.out.println("String is: " + strBuffer );
// printing the hashcode of the object strBuffer
System.out.println("Hashcode of the String Buffer object is: " + strBuffer.hashCode());
// doing the concatenation work
strBuffer.append("Tutorial & Example");
System.out.println("\nString is: " + strBuffer );
// printing the hashcode of the object strBuffer
System.out.println("Hashcode of the String Buffer object is: " + strBuffer.hashCode());
} 
}  

Output:

 Performing The Hash Code test for String:
String is: Hi
Hashcode of the string object is: 72479
String is: Hi Tutorial & Example
Hashcode of the String object is: -1969955187
Performing The Hash Code test for the StringBuffer:
String is: Hi
Hashcode of the String Buffer object is: 1282788025
String is: Hi Tutorial & Example
Hashcode of the String Buffer object is: 1282788025 

Explanation: For the strings of the class String, the hash code is different when the string is manipulated, that shows the immutability of the class String. For the StringBuffer class, the hash code is same even after the manipulation showing that strings are not immutable in the StringBuffer class.


Related Topics

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.