Page 1 of 1

Variable Assignment Having No Effect

Posted: Thu Feb 21, 2013 3:30 pm
by Sweetpin2
Hi,

For below code

public class Test_Assignment {

static int x;

public static void main(String[] args) {
int x = 10;
x = x;
System.out.println(x);

}

}

The code prints 10. Why the assignment x(local variable) = x(static variable initialized with 0) has no effect.

Re: Variable Assignment Having No Effect

Posted: Thu Feb 21, 2013 6:49 pm
by admin
In your statement x = x; How will the compiler know which x is which?
So the rule is local variable x shadows the static variable x.
You should do x = Test_Assignment.x; if you want to assign the value of static x to local x.