I am working on Marcus Green Java Programmer Certification Mock Exam No 1.
On the question 19,
What will happend when you attempt to compile and run the following code?
public class Tux extends Thread{
static String sName = "vandeleur";
public static void main(String argv[]){
Tux t = new Tux();
t.piggy(sName);
System.out.println(sName);
}
public void piggy(String sName){
sName = sName + " wiggy";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
}
}
}
1) Compile time error
2) Compilation and output of "vandeleur wiggy"
3) Compilation and output of "vandeleur wiggy 0 1 2 3"
4) Compilation and probably output of "vandeleur" but possible output of "vandeleur 0 1 2 3"
The answer is 4)
It says that "...
Just because sName is static does not mean that passing it to a method gives the method the original copy. The method only sees a locally created copy and any changes to it will not be reflected on return to the calling method. "
Calling the fucntion piggy(String sName) actually passes a String object reference into the function, so after the statement in the piggy function - sName = sName + " wiggy" is execuated, the sName should point to a string that is changed.
So before start the thread, the static sName actually already point to " vandeleur wiggy".
Am I wrong somewhere or the answer is wrong?
Thanks,
Iris