Saturday, 11 February 2012

What will be the result of an attempt to compile and run the following program?

class Test
{

public static void main(String args[])
{


String s1 = "abc";
String s2 = "abc";
s1 += "xyz";
s2.concat("pqr");
s1.toUpperCase();
System.out.println(s1 + s2);


}


}

Choices:

  • A. "abcxyzabc"

  • B. "abcxyzabcpqr"

  • C. "ABCXYZabcpqr"

  • D. "ABCXYZabc"

  • E. Code does not compile


Correct choice:

  •  A


Explanation:

This code compiles and runs without errors, printing "abcxyzabc." In the given code, s1 and s2 initially refer to the same String object "abc." When "xyz" is concatenated to s1, a new String object "abcxyz" is created and s1 is made to refer to it. Note that s2 still refers to the original String object "abc," which is unchanged. The concat() and toUpperCase() methods do not have any effect, because the new String objects created as a result of these operations do not have any references stored. So s1 contains "abcxyz" and s2 contains "abc" at the end, making A the correct result.

No comments:

Post a Comment