March 01, 2015

Which code fragment, inserted at line 24, outputs "123abc 123abc"?

Given:

22. StringBuilder sb1 = new StringBuilder("123");
23. String s1 = "123";
24. // insert code here
25. System.out.println(sb1 + " " + s1);



A. sb1.append("abc"); s1.append("abc");
B. sb1.append("abc"); s1.concat("abc");
C. sb1.concat("abc"); s1.append("abc");
D. sb1.concat("abc"); s1.concat("abc");
E. sb1.append("abc"); s1 = s1.concat("abc");
F. sb1.concat("abc"); s1 = s1.concat("abc");
G. sb1.append("abc"); s1 = s1 + s1.concat("abc");
H. sb1.concat("abc"); s1 = s1 + s1.concat("abc");









Answer: E

Explanation:

public StringBuilder append(String s) :is used to append the Specified String with the given String. Here sb1 is a reference variable of type of StringBuilder which has 123 as String in it. 

Now we need to append 123 with abc so we call sb1.append("abc"); which gives the output 123abc and remember unlike normal String where operation on 2 strings forms new String which doesn't affect the original given String but in String Builder it does affect the original String when we are using append method, therefore 123abc is stored in sb1 itself .


Next we are declaring String s1 as 123 and concat with String abc which gives new String 123abc .Now in-order to change the contents of original String s1 we store new String 123abc in s1 by writing s1 = s1.concat("abc"); .


By SOP of sb1 and s1 seperated by blank space we get the output as 123abc 123abc.Option E.

Related Topics

0 comments:

Post a Comment