This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explaining output regarding static methods

 
Shanel Jacob
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi the following code compiles fine. What I'm trying to understand is that why is it that when "x" is incremented to 1 in the "increment" method. It's value is 'lost' when trying to display "x" in the "main" method?

 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Technically, all parameters in Java are pass-by-value.
Are parameters passed by reference or passed by value in method invocation?
[ July 21, 2006: Message edited by: wise owen ]
 
Balaji Sampath
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The basic concept is , when you declare the inner or local variable that has the same name has the class or instance variable then the inner variable shadows the outer variable. This concept is called shadowing of variables.

Thanks
Balaji.S
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



The problem is that the parameter int x in the increment method is hiding the static int x defined in the class. All changes to x in the increment method remain local to the method. If (within increment) you wish to modify the static int x's value you have to refer it using the class name: Incrementor.x
[ July 21, 2006: Message edited by: Barry Gaunt ]
 
Shanel Jacob
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic