×

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

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

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.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? 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 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.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.