• Post Reply 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:

Static Initialization Sequence

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Look! It's Leonardo da Vinci! And he brought a tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic