×

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 Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

String isnullorempty in Java

What do you mean by String? 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...

4 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.