• Post Reply Bookmark Topic Watch Topic
  • New Topic

Order of initialisation of static variables  RSS feed

 
petr pavlovich
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why output 5???
i do n't know.


explain me, please.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about the order things happen in. instance and BASE are both static variables. They'll be initialised in the order they appear. But DELTA is a constant - it will have the value 5 whenever it's referred to (in fact the compiler may decide to replace every reference to DELTA with 5 to optimise things).
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, in the future, please UseAMeaningfulSubjectLine(⇐click) so people will know at a glance whether your problem is something they might be interested in.

As for your quesiton, the new Tasks() on line 2 runs before the DELTA and BASE assignment lines. Since BASE hasn't yet been assigned, it still has its default value of 0 when we do the addition inside the constructor.

HOWEVER since DELTA is final, it's a compile-time constant, and every use of DELTA gets replaced with the constant 5. At runtime, we're not actually evaluating DELTA to get its value.

So the body of the c'tor is really


and when the runtime goes to evaluate BASE, it hasn't been set yet, so we get 0 + 5.

Of course, anybody who writes code like that for real should have his computer taken away forever.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff Verdegan wrote:First, in the future, please UseAMeaningfulSubjectLine(⇐click) so people will know at a glance whether your problem is something they might be interested in.

(Fixed)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!