-1

What is the disadvantage of:

for(int i=0;i<10;i++)
{
    String str = ""+i;
    System.out.println(str);
}

over:

 String str;
 for(int i=0;i<10;i++)
 {
     str = ""+i;
     System.out.println(str);
 }

and:

 for(int i=0;i<10;i++)
 {
     StringBuilder strBld = new StringBuilder("Hello"+i);
     System.out.println(strBld.toString());
 }

With respect to total number of object created in memory?

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Nikhil
  • 849
  • 8
  • 10

1 Answers1

1

Number of Object created in all three scenario are same .

You can verify the same using

 Runtime rt = Runtime.getRuntime();
 System.out.println("Free: " + rt.freeMemory());
  for(int i=0;i<10;i++)// To get a measurable diffrence iterate upto higher value
  {
     String str = ""+i;
     System.out.println(str);
  }
  System.out.println("Free: " + rt.freeMemory());

so their is no disadvantage based upon no of objects created .

if you want to know when to use StringBuilder in java over String Check mentioned link .

Community
  • 1
  • 1
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62