my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ///[Thread]/// Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "///[Thread]///" Watch "///[Thread]///" New topic


chao-long liao
Ranch Hand

Joined: Jul 29, 2001
Posts: 78
Marcus Green mock exam....
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();
public void piggy(String sName){
sName = sName + " wiggy";
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,and here is the explain,If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the method piggy the main method will run to completion and the value of sName will still be vandeluer before the Thread modifies it. You cannot be certain of this though.
I can't understand what it say,somebody help me please.
Amir Ghahrai
Ranch Hand

Joined: Jun 19, 2002
Posts: 110
I thought the answer should always be the same regardless of the underlying OS.
String objects are immutable.
Even though you call the piggy method,
the change is local to the method but the original String object sName doesn't change.
so it should always return the string vandeleur.

Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
The run method creates new string objects and assign them to the field sName. Thus if the run method is executed before the println statement, the output is not going to be vandeleur only.

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link:
subject: ///[Thread]///
It's not a secret anymore!