• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Explaining output regarding static methods

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for your explanation.
reply
    Bookmark Topic Watch Topic
  • New Topic