• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables

 
David Sabate
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21021
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hint: what happens when you have a static variable and a local variable with the same name?
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, all clear now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic