A disadvantage of String in a loop or Why String Buffer, String Builder used in the loop.
String class is immutable in java when you try to put a string in a loop and try to perform some operation on that string or modifications.


It generates too many objects in heap and wastes your memory if you try to modify it too many times. So if you want to do any modifications to your string, don't use strings in a loop or without loop.

String internally uses StringBuffer (till Java 1.4) or StringBuilder (Java 1.5 onwards) for String concatenation “+" or concat().
String concatenation is implemented internally through Java StringBuilder class(1.5) using its append method it automatically converts string concatenation.
If you try to use a string in a loop and tried to do some concatenation on that then this type of concatenation is performed on a loop which is 0(n) time, StringBuilder object is created for each iteration in the loop. INTERVIEW QUESTION  WHEN TO USE STRING, STRING BUFFER, STRING BUILDER

Let's see an example Disadvantage of String in a loop.

In this below example, we are trying to concat the string or performing some operation on the String in a loop, StringBuilder object is created for each iteration in the loop.


public class StringInLoop {
  public static void main(String[] args) {

   String input = new String();

   for (int i = 0; i < 10; i++) {
    input = input + i;
    System.out.println(i + 1 + ":" + input.hashCode());
   }
  }
 }


OUTPUT:
1:48
2:1537
3:47697
4:1478658
5:45838450
6:1420992003
7:1101079187
8:-226283516
9:1575145652
10:1584875013


In this below example, we are trying to concatenate using StringBuilder as you can see the StringBuilder object is not created for each iteration in the loop.
So it is better to use StringBuilder and  StringBuffer while performing some operation or modification on a String.


public class StringInLoop {
  public static void main(String[] args) {

   StringBufferinput = new StringBuffer();

   for (int i = 0; i < 10; i++) {
    input = input + i;
    System.out.println(i + 1 + ":" + input.hashCode());
   }
  }
 }

OUTPUT:
1:1829164700
2:1829164700
3:1829164700
4:1829164700
5:1829164700
6:1829164700
7:1829164700
8:1829164700
9:1829164700
10:1829164700


 Below example, we are trying to Calculate free memory while performing an operation on String.

public class StringInLoop {
  public static void main(String[] args) {

   Runtime rt = Runtime.getRuntime();
   String input = new String();
   System.out.println("Free: " + rt.freeMemory());

   // To get a measurable difference iterate up to higher-value
   for (int i = 0; i < 100; i++) {
    input = input + i;
   }
   System.out.println("Free: " + rt.freeMemory());
  }
 }

Post a Comment

أحدث أقدم