• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I am confused abt this code

 
vuthlarhi donald
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Tux extends Thread{
static String sName = "Techno";
public static void main(String argv[]){
Tux t = new Tux();
t.name(sName);
System.out.println(sName);
}
public void name(String sName){
sName = sName + " park";
start();}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i; }} }
 
Panseer Kaur
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are you confused about exactly?
 
vuthlarhi donald
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
about what the program prints
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


These two lines has clue for you.
 
Sid Robin
Ranch Hand
Posts: 53
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, note that the formal parameter "sName" of name() shadows the class variable with the same name. In other words, within the body of name(), the variable "sName" refers only to the parameter passed to it, not the variable defined by 'static String sName = "Techno"'.
 
mohan gavande
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think o/p would be "Tachno park 3".
And also it will print after the thread execution.
right???
 
Lukas Zuchowski
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's concurency issue.
I usualy prints "Techno", but when I was following the execution in debuger,
the thread that program was starting by "start();" has finished execution before "System.out.println(sName)" was executed and the result was : "Techno 1 2 3 4".
In conclusion I think we can't be sure what will be printed in this case.

ps. but definitly nothing that starts from "Techno Park"
 
Hasitha Randika
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it will print techno until the loop ends what you want to remember is Strings are immutable so it will print techno
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic