Why should you be careful about String concatenation (+) operator in loops using Java?


Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

Public class Sample{
   Public static void main(String args[]){
      String str1 = "Hello";
      String str2 = "how are you";
   }
}

Strings are immutable in Java i.e. once you create a String literal it cannot be modified.

Storage

Since all the String values we define are objects of the String class they are stored on the heap area. But, unlike other objects in a separate memory location known as String Constant pool is allotted for the String objects.

Whenever you define a String value JVM creates a String object with the given value in the String constant pool. Therefore, if you run the above program two String values are created in the String constant pool.

Concatenation of two Strings

If you try to concatenate these two String values as −

str1 = str2 + str2;

Since Strings are immutable in java, instead of modifying str1 a new (intermediate) String object is created with the concatenated value and it is assigned to the reference str1.

If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues. Therefore, concatenating strings in loops as shown in the following example is not recommended.

Example

public class StringExample {
   public static void main(String args[]) {
      String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"};
      String singleString = new String();
      for (int i=0; i<stringArray.length; i++) {
         singleString = singleString+stringArray[i]+" ";
      }
      System.out.println(singleString);
   }
}

Output

Java JavaFX HBase Oracle

Example

If you have a scenario to add String values in loops it is recommended to use StringBuilder instead of Strings −

public class StringExample {
   public static void main(String args[]) {
      String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"};
      StringBuilder singleString = new StringBuilder();
      for (int i=0; i<stringArray.length; i++) {
         singleString.append(stringArray[i]);
         singleString.append(" ");
      }
      System.out.println(singleString);
   }
}

Output

Java JavaFX HBase Oracle
raja
Published on 05-Aug-2019 15:15:19
Advertisements