Java OCA OCP Practice Question 210

Question

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?

  • A. Less than 10
  • B. About 1000
  • C. About 2000
  • D. About 3000
  • E. About 4000


B is correct.

Note

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.




PreviousNext

Related