Given:
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String s = new String(); for(int i = 0; i < 1000; i++) { s = " " + i; sb.append(s);/* w w w . j a va 2 s .co m*/ } // done with loop } }
If the garbage collector does NOT run while this code is executing, approximately how many objects will exist in memory when the loop is done?
B is correct.
StringBuilders are mutable, so all of the append()
invocations are acting upon the same StringBuilder object over and over.
Strings are immutable.
Every String concatenation operation results in a new String object.
The string " " is created once and reused in every loop iteration.