File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads question 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 "Threads question" Watch "Threads question" New topic

Threads question

Nikhil Shah Jain
Ranch Hand

Joined: Apr 21, 2009
Posts: 31

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

Joined: Dec 10, 2009
Posts: 521
the local variable sName shadows the class variable sName

scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later" someone unknown
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

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...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Nikhil Shah Jain
Ranch Hand

Joined: Apr 21, 2009
Posts: 31
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

Joined: Apr 21, 2009
Posts: 31
Is it because run has been called statically and name through reference variable?
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
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.

SCJP 1.6 96%
I agree. Here's the link:
subject: Threads question
It's not a secret anymore!