Bookmark Topic Watch Topic
  • New Topic

Shadowing Variables  RSS feed

Posts: 5
  • Mark post as helpful
  • send pies
  • 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);
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.
Wink, wink, nudge, nudge, say no more, it's a tiny ad:
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!