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?
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?
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();