×

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

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

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

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.