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 static variables 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 "static variables" Watch "static variables" New topic

static variables

David Sabate

Joined: Feb 25, 2013
Posts: 10

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 Sabate

Joined: Feb 25, 2013
Posts: 10
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

Joined: Apr 06, 2010
Posts: 4543

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

Joined: Sep 28, 2004
Posts: 20521

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: 262
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

Joined: Feb 25, 2013
Posts: 10
Thanks guys, all clear now.
I agree. Here's the link:
subject: static variables
It's not a secret anymore!