File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads question

 
Nikhil Shah Jain
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Can some one explain why Java is never printed and why output possibilities are "Sun" and "Sun 0 1 2 3"
 
Raju Champaklal
Ranch Hand
Posts: 521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the local variable sName shadows the class variable sName
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Raju pointed out, the statement sName = sName + " Java"; is meant to confuse you. The static variable sName's value doesn't change in name() method. The output possibilities are not just "Sun" and "Sun 0 1 2 3", but also "Sun 0", "Sun 0 1" and "Sun 0 1 2". The reason is simple, the println statement in main method can run anytime while the run method is iterating, thus the value of sName can be anything out of the above 5 possible values when println statement in main method runs...
 
Nikhil Shah Jain
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But both these methods are modifying sNAme in the same way, still run method is successful in overwriting sName, why is this?
 
Nikhil Shah Jain
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it because run has been called statically and name through reference variable?
 
Neha Daga
Ranch Hand
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in name method you have a local variable named sname which shadows the instance variable and the concatenation is done on the local variable sname but in run method there is no local variable it is using the instance variable only so what ever is done it will modify the instance variable sname.

I hope you get it now.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic