Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about thread

 
wei liu
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 "vandelur" but possible output of "vandeleur 0 1 2 3"
ans: 4) Compilation and probably output of "vandelur" but possible output of "vandeleur 0 1 2 3"
my question is that why there are two possibilities?
 
Tony Sam
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
becoz method run() may possible exexcute after
System.out.println(sName);

 
wei liu
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought the ans was c ,since the code will first run t.piggy(sName);secondly System.out.println(sName);in that case the result should be c.
what is the wrong point of my view?

Originally posted by wei liu:
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 "vandelur" but possible output of "vandeleur 0 1 2 3"
ans: 4) Compilation and probably output of "vandelur" but possible output of "vandeleur 0 1 2 3"
my question is that why there are two possibilities?

 
prawith thowphant
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friend.
look at piggy mehtod.
at line sName = sName + " wiggy";
now sName is not reference to sName that data member of class.
because, String it cannot chage the value.
 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your view is right if

SomeObject.sName = sName + " wiggy";
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic