This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 4343
    
    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: 18538
    
  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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: static variables
 
Similar Threads
Thread Question from "Java Certifications" SCJP 1.6 Mock Exam Practice Questions
static variable remains unchanged
String Immutability
Thread - Please explain!
local scope of String variable