How to Optimize String Concatenation in Java?
Last Updated :
02 Dec, 2020
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.
Concatenation is the process of joining end-to-end. Let us take an example to understand what concatenation means in English.
Person 1 speaking to Person 2 - ItsCodingEra
Person 2 speaking to Person 1 - 2020India
Now, let us carry a process whose output is as follows- ItsCodingEra2020India
This process is called concatenation.
Example:
Input String = "Geeks" + "for" + "Geeks";
OutputString = "GeeksforGeeks" ;
There are numerous ways by which we can tell computers to do so which are called methods. Let us describe how a computer can perform an action via our methods in different ways.
This action can take place via 4 methods :
- Using ‘+’ operator
- Using concat() inbuilt method
- Using StringBuilder
- Using StringBuffer
Lets us describe and implement them one by one.
Method 1: String Concatenation using ‘+’ Operator
Java
import java.lang.*;
class GFG {
public static void main(String[] args)
{
String str = "" ;
long startTime = System.currentTimeMillis();
for ( int i = 0 ; i < 100000 ; i++) {
str += Integer.toString( 0 );
}
long endTime = System.currentTimeMillis();
System.out.println(
"Time taken to concatenate 100000 Strings using '+' operator : "
+ (endTime - startTime) + " ms" );
}
}
|
Output
Time taken to concatenate 100000 Strings using '+' operator : 2126 ms
Method 2: using concat() Inbuilt function
Concat(String str) method concatenates the specified String to the end of this string. This method appends the specified string at the end of the given string and returns the combined string.
Example :
String str="GeeksforGeeks";
s1 = s1.concat(".").concat("com");
Java
import java.lang.*;
class GFG {
public static void main(String[] args)
{
String str = "" ;
long startTime = System.currentTimeMillis();
for ( int i = 0 ; i < 100000 ; i++) {
str.concat(Integer.toString( 0 ));
}
long endTime = System.currentTimeMillis();
System.out.println(
"Time taken to concatenate 100000 Strings using concat() method : "
+ (endTime - startTime) + " ms" );
}
}
|
Output
Time taken to concatenate 100000 Strings using concat() method : 46 ms
Method 3: By using StringBuilder (Best Way)
StringBuilder represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.
Example :
StringBuilder str = new StringBuilder();
str.append("GFG");
Time Complexity for concatenation using StringBuilder method:
Java
import java.lang.*;
class GFG {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder();
long startTime = System.currentTimeMillis();
for ( int i = 0 ; i < 100000 ; i++) {
str.append( 0 );
}
long endTime = System.currentTimeMillis();
System.out.println(
"Time taken to concatenate 100000 Strings using StringBuilder append : "
+ (endTime - startTime) + " ms" );
}
}
|
Output
Time taken to concatenate 100000 Strings using StringBuilder append : 34 ms
Method 4: By using StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.
Example :
StringBuffer s = new StringBuffer("GeeksforGeeks");
Java
import java.lang.*;
class GFG {
public static void main(String[] args)
{
StringBuffer str = new StringBuffer();
long startTime = System.currentTimeMillis();
for ( int i = 0 ; i < 100000 ; i++) {
str.append( 0 );
}
long endTime = System.currentTimeMillis();
System.out.println(
"Time taken to concatenate 100000 Strings using StringBuffer append : "
+ (endTime - startTime) + " ms" );
}
}
|
Output
Time taken to concatenate 100000 Strings using StringBuffer append : 41 ms
Similar Reads
How to Concatenate Multiple Strings in Java?
In Java programming, there are a lot of ways to concatenate multiple strings. For this, we have taken three or more String values then we concatenate those String values by using different ways. In this article, we have used two different ways, we will explain each method with one example for a bett
2 min read
Convert LinkedList to String in Java
A LinkedList is a linear data structure, in which the elements are not stored at contiguous memory locations. For converting a linked list to a string we need to traverse the linked list and after that, we need to append the element of the linked list to the string variable. We can use String class,
4 min read
Java Program to Create String from Contents of a File
A File is a computer resource which is deployed to store different types of data such as text, image, video, to name a few. It is basically a collection of data bound to a single entity. While using your computer, it becomes essential to be able to deal with files and in this article we will be lear
6 min read
How to Find the Longest Common Prefix of Two Strings in Java?
In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: âgeeâ Input: String 1= flower, String 2 = flightOutput: âflâ Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by whi
4 min read
Java Program to Concatenate Two List
Concatenating two lists means merging two lists into a single list. Consider the given lists: There are several methods to perform concatenation operation: Using addAll() methodUsing streamUsing union() Method 1: Using addAll() method Syntax: addAll ( list name ) This method takes name of list as ar
3 min read
Check for string rotation in Java
In Java, to check if one string is a rotation of another, we can do string concatenation and substring matching. A rotated string is created by moving some characters from the beginning of the string to the end while maintaining the character order. Program to Check if One String is a Rotation of An
2 min read
How to Convert a Comma-Separated String into an ArrayList in Java ?
In Java, to convert a comma-separated string into ArrayList, we can use the split() method to break the string into an array based on the comma delimiter. Another method we can also use Java Streams for a functional approach to achieve the same result. Example: Input: "Hello,from,geeks,for,geeks"Out
2 min read
How to concatenate two Integer values into one?
Given two integers n1 and n2, the task is to concatenate these two integers into one integer.Example: Input: n1 = 12, n2 = 34 Output: 1234 Input: n1 = 1, n2 = 93 Output: 193 Approach: The simplest approach to do this is: Convert both numbers to stringConcatenate both strings into one, as this is com
4 min read
How to Print Fast Output in Competitive Programming using Java?
In Competitive programming, most of the students use C++ as their primary language as it is faster than the other languages(e.g Java, Python) but for a student/professional who use Java as his/her primary language taking Input from input streams and printing fast output is the main difficulty faced
2 min read
How to Split a String into Equal Length Substrings in Java?
In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list. Example: In t
3 min read