-1

a question from the Java interview preparation that I didn't find an answer to

Why is it not recommended to change strings in a loop? What is recommended to use?

D.Nursultan
  • 55
  • 2
  • 8

1 Answers1

2

Strings are immutable objects and therefore possibly the compiler has to create at least one new object to hold the result when appending to strings. Constructing a string in a loop requires creating a new string in every iteration and therefore consuming more time and memory. This will affect the performance of the algorithm badly.

This provides a solution to update strings using StringBuffer or StringBuilder.

r = new Random(120);
StringBuilder sb = new StringBuilder();

for(int i=0; i<100; i++) {
    sb.append(r.nextInt(2));
}
s = sb.toString();
Thamindu DJ
  • 1,679
  • 4
  • 16
  • 29
  • 1
    And for s smidgen more efficiency, you could preallocate the buffer: `new StringBuilder(100)` -- the size given should be more than you expect to need, but not absurdly so. Here it's easy to figure out. – user13784117 Jul 25 '20 at 13:53