Skip to content
Related Articles

Related Articles

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to concatenate string
import java.lang.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        String str = "";
  
        // timer-start time
        long startTime = System.currentTimeMillis();
  
        for (int i = 0; i < 100000; i++) {
            // string concatenation
            str += Integer.toString(0);
        }
  
        // timer-end time
        long endTime = System.currentTimeMillis();
  
        // display the result
        System.out.println(
            "Time taken to concatenate 100000 Strings using '+' operator : "
            + (endTime - startTime) + " ms");
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to concatenate string
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");
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to concatenate string
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");
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to concatenate string
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");
    }
}

chevron_right


Output

Time taken to concatenate 100000 Strings using StringBuffer append : 41 ms

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :