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
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Shadowing Variables

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
package ShadowVariable;

class Foo {

static int size=7;

static void changeIt(int size){
size = size + 200;
System.out.println("size inside changeIt " + size);
}

public static void main(String[] args) {
System.out.println("Before modify size variable " + size);
changeIt(size);
System.out.println("size After changeIt " + size);
}
}

The output of this program is :
-------------------------------
Before modify size variable 7
size inside changeIt 207
size After changeIt 7


Am little bit confused about the behaviour of this program's output.
As per my knowledge,here SIZE is a static variable and it should be unique.
I believe that is main purpose of static variables and it is accessed globally without creating instance of it.

But here in the changeIt(int size) method, as soon as we create the local(method) variable as the same name of static variable, the global variable is shadowed(hidden) by the local variable.

I thought the output is like :
Before modify size variable7
size inside changeIt207
size After changeIt 207

because size is global variable and unique as it is static.

Could you please explain how it is working and what is the priority and scope of both method(local) variable and static(global) variable.
 
He does not suffer fools gladly. But this tiny ad does:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
    Bookmark Topic Watch Topic
  • New Topic