What is the output of the following JAVA program ? Class Test { public static…
2017
What is the output of the following JAVA program ?
Class Test
{
public static void main (String [] args)
{
Test obj=new Test ();
obj.start ();
}
void start()
{
String stra="do";
String strb=method (stra);
System.out.print(":" +stra +strb);
}
String method (String stra)
{
stra=stra+"good";
System.out.print(stra);
return "good";
}
}
- A.
dogood : dogoodgood
- B.
dogood : gooddogood
- C.
dogood : dodogood
- D.
dogood : dogood
Attempted by 125 students.
Show answer & explanation
Correct answer: D
Explanation: step through what the program prints and returns.
In start(), stra is initialized to "do" and method(stra) is called.
Inside method, a new local parameter variable is used. It is reassigned as stra = stra + "good" producing "dogood" and then System.out.print(stra) prints "dogood".
The method returns the string "good" (it does not return "dogood").
Back in start(), the original stra is still "do" (strings are immutable and the method's reassignment did not change the caller). strb receives the returned value "good".
System.out.print(":" + stra + strb) prints ":" followed by "do" and "good", producing ":dogood".
Final combined output: dogood:dogood