Java OCA OCP Practice Question 293

Question

Given:

 3. public class Main {
 4.   public static void main(String[] args) {
 5.     String s1 = "abc";
 6.     String s2 = s1;//from w  w w .j  av  a  2 s .  co m
 7.     s1 += "d";
 8.     System.out.println(s1 + " " + s2 + " " + (s1==s2));
 9.
10.     StringBuffer sb1 = new StringBuffer("abc");
11.     StringBuffer 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

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

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

StringBuffer objects are mutable, so the append() is changing the single StringBuffer object to which both StringBuffer references refer.




PreviousNext

Related