×

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

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

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

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

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

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.