• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Puzzler

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Case 1 - assign
static int x = 10;
a new value within main:

Within the 'main' method one line 2, when x=5; the output will be 10 .

The value of the static variable on line 1 will be changed to 5 (will be assigned a new value within the main method).
For Case 1 where 'x' is not declared as a local variable on line 2,
line 1 is changed by the assignment statement on line 2, therefore altering the values of 'x' and 'y' declared in the class.

Case 1:

_______________________________________________________________

Case 2:
Case 2 : Declare x as a local variable of main :
int x = 5;
and the output is changed to 20.


_______________________________________________________________

Because an object is created on line 3, the static variable on line 1 is associated with the instance created on line 3.
When 'x' is declared as a local variable
int x = 5; // line 2
it will not alter the value which has been assigned on line 1.

Please confirm.



 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case 1, you are reassigning the static instance variable to 5 and in case 2, you are shadowing the static instance variable x with a new declaration in your method. This new declaration does not have anything to do with the static instance variable x. Your understanding is absolutely correct.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic