wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static variables" Watch "static variables" New topic
Author

static variables

David Sabate
Greenhorn

Joined: Feb 25, 2013
Posts: 8
Hi,

Please, can someone explain me the output of this code? I was expecting 'good idea 0 1 2 3' not 'good 0 1 2 3'.

Many thanks,
David

David Sabate
Greenhorn

Joined: Feb 25, 2013
Posts: 8
Actually I'm just seeing that some of the executions result in 'good' and some of them end up in 'good 0 1 2 3'
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4366
    
    8

In your nameTest() method, you have two sName variables in scope. There is the static variable, and there is the method parameter. And the latter is hiding the former, so the static variable is completely unaltered by that method.

Then the reason why you get two different possible outputs is that the two threads can be run in either order. So there is no guarantee whether the System.out.println() will run before or after the run() method executes. In fact, it's also possible for it to partially execute: "good 0", "good 0 1" and "good 0 1 2" are also possible outputs.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18748
    
  40


Hint: what happens when you have a static variable and a local variable with the same name?

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Heena Agarwal
Ranch Hand

Joined: Dec 25, 2013
Posts: 261
    
    4
Hint : What happens if you change the method as follows.


Run your code with these changes. Now does that explain what is happening?
David Sabate
Greenhorn

Joined: Feb 25, 2013
Posts: 8
Thanks guys, all clear now.
 
Don't get me started about those stupid light bulbs.
 
subject: static variables