It's not a secret anymore!*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA 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: 10
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



OCPJP6
David Sabate
Greenhorn

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
Bartender

Joined: Apr 06, 2010
Posts: 4377
    
    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: 18765
    
  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: 10
Thanks guys, all clear now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variables