×

String vs StringBuilder

String vs StringBuilder

In this section, we will discuss the comparison between Java String and StringBuilder class.

String

In Java, a string is treated as an object that represents a sequence of characters. The String class is present in java.lang package. In Java, a String object is always immutable.

StringBuilder

The StringBuilder class is used to create mutable strings. The StringBuilder is same as the StringBuffer class. The difference is StringBuilder class is not synchronized whereas, the StringBuffer class is synchronized.

The following table highlights the key points by comparing the String class with the StringBuilder classin Java.

StringStringBuilder
String is an immutable class.StringBuilder is a mutable class.
Manipulation of string is slow in the String class.Concatenation of string is quick in StringBuilder class as compared to the StringBuffer class.
Comparison of two strings can be made using the equals() method.Similar to StringBuffer, the StringBuilder class does not override the equals() method of the Object class. Hence, a comparison of two strings using the equals() method can not be made.

Performance Difference Between String and StringBuffer


The following comparison is based on the basis of the concatenation of strings for the String class and the StringBuilder class.

FileName: PerformanceTestExample.java

 // A basic Java program that compares the performance of String and StringBuilder
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 the StringBuilder class
StringBuilder strBuilder = new StringBuilder("Hi "); 
for (int j = 0; j < 10000; j++)
{ 
    // doing the concatenation work
    strBuilder.append("Tutorial & Example"); 
} 
// displaying the time taken by StringBuilder
System.out.println("Total Time consumed by the StringBuilder is: " + (System.currentTimeMillis() - sTime) + "ms");
} 
}  

Output:

 Total Time consumed by the String is: 612ms
Total Time consumed by the StringBuilder is: 5ms 


Explanation: Similar to StringBuffer, the StringBuilder class also takes less time as compared to the String class. The reason behind this is the time for doing the appending work is less, as the StringBuilder class is also mutable, whereas, for the String class, the time consumption is more as the String class is immutable. The immutable property of the String class leads to the creation of a new string whenever the string is manipulated. The creation of the new string, upon manipulation, is absent in the StringBuilder class.

Hash Code Test for String and StringBuilder

In the previous example, we have learned that whenever a string is manipulated, a new string is created for the String class. However, the same is not true for the StringBuilder 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 StringBuilder
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("Hello "); 
System.out.println("String is: " + str );
// printing the hash code of the object str
System.out.println("Hash code of the string object is: " + str.hashCode());
// doing the concatenation work
str += ("Tutorial & Example "); 
System.out.println("\nString is: " + str);
// printing the hash code of the object str
System.out.println("Hash code of the String object is: " + str.hashCode()); 
System.out.println("\nPerforming The Hash Code test for the StringBuilder: \n");
// creating an object of StringBuilder
StringBuilder strBuilder = new StringBuilder("Hello "); 
System.out.println("String is: " + strBuilder );
// printing the hash code of the object strBuilder
System.out.println("Hash code of the String Builder object is: " + strBuilder.hashCode());
// doing the concatenation work
strBuilder.append("Tutorial & Example");
System.out.println("\nString is: " + strBuilder );
// printing the hash code of the object strBuilder
System.out.println("Hash code of the String Builder object is: " + strBuilder.hashCode());
} 
}       

Output:

 Performing The Hash Code test for String:
String is: Hello
Hash code of the string object is: -2137068114
String is: Hello Tutorial & Example
Hash code of the String object is: -443899836
Performing The Hash Code test for the StringBuilder:
String is: Hello
Hash code of the String Builder object is: 314337396
String is: Hello Tutorial & Example
Hash code of the String Builder object is: 314337396 

Explanation: It is evident by looking at the output that, for the StringBuilder class, the hash code remains the same even after the manipulation (append work) of the string. Because of the immutability feature of the String class, the hash code changes every time when the manipulation of string is done.


Related Topics

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

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.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.