Java OCA OCP Practice Question 2835

Question

Given:

42.  String s1 = " ";  
43.  StringBuffer s2 = new StringBuffer(" ");  
44.  StringBuilder s3 = new StringBuilder(" ");  
45.  for(int i = 0; i < 1000; i++) // Loop #1  
46.    s1 = s1.concat("a");  
47.  for(int i = 0; i < 1000; i++) // Loop #2  
48.    s2.append("a");  
49.  for(int i = 0; i < 1000; i++) // Loop #3  
50.    s3.append("a"); 

Which statements will typically be true? (Choose all that apply.)

  • A. Compilation fails.
  • B. Loop #3 will tend to execute faster than Loop #2.
  • C. Loop #1 will tend to use less memory than the other two loops.
  • D. Loop #1 will tend to use more memory than the other two loops.
  • E. All three loops will tend to use about the same amount of memory.
  • F. In order for this code to compile, the java.util package is required.
  • G. If multiple threads need to use an object, the s2 object should be safer than the s3 object.


B, D, and G are correct.

Note

StringBuffer object's methods are synchronized, which makes them better for multiple threads, and typically a little slower.

Because String objects are not mutable, Loop #1 is likely to create about 1000 different String objects in memory.




PreviousNext

Related