• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Initialization Sequence

 
Yan Bai
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


It compiles and prints out '0'. Isn't it a forward reference at line 2 since p is not complete its initialization yet?
Thanks for your explanation.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
p starts out with its default value (0). Line 2 is not a "forward reference" because it comes after line 1 in the source code.
 
Yan Bai
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ron Newman:
p starts out with its default value (0). Line 2 is not a "forward reference" because it comes after line 1 in the source code.

Thanks Ron. So how about final static variables, will they get a default value also? The following works, but does this mean that the value of final static variable can be changed?
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is indeed possible for a supposedly "final" static variable to change its value this way. I modified your code to the following:

which prints out:
0
123
I'd like to see the compiler generate a warning for cases like this, but it doesn't.
[ October 31, 2002: Message edited by: Ron Newman ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic