Java OCA OCP Practice Question 208

Question

Given:

3. public class Main {
4.   public static void main(String[] args) {
5.     String s1 = "abc";
6.     String s2 = s1;/* w w w.j ava 2s  .c  o  m*/
7.     s1 += "d";
8.     System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10.     StringBuilder sb1 = new StringBuilder("abc");
11.     StringBuilder sb2 = sb1;
12.     sb1.append("d");
13.     System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14.   }
15. }

Which are true?

Choose all that apply.

A.   Compilation fails
B.   The first line of output is abc abc true
C.   The first line of output is abc abc false
D.   The first line of output is abcd abc false
E.   The second line of output is abcd abc false
F.   The second line of output is abcd abcd true
G.   The second line of output is abcd abcd false


D and F are correct.

Note

Although String objects are immutable, references to Strings are mutable.

The code s1 += "d"; creates a new String object.

StringBuilder objects are mutable.

so the append() is changing the single StringBuilder object to which both StringBuilder references refer.




PreviousNext

Related