×

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

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 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 Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.