Meaningless Drivel is fun!
The moose likes Java in General and the fly likes instance variable and initilization block : control flow Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "instance variable and initilization block : control flow" Watch "instance variable and initilization block : control flow" New topic

instance variable and initilization block : control flow

Vishwadeep Aggarwal

Joined: Oct 30, 2012
Posts: 8

Q: Here the question is that we are using the instance variable m before defining and initializing it but while compiling and executing this code it didn't show error. Also, if JVM first define and initialize the variable m then code must generates output as 3 2 1 but in actual the code generates the output as 2 3 1
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

The sequence of events when initializing class instances are described in the JLS here. The key points that affect this sample code:

  • Instance variables are initialized to their default values
  • A constructor is chosen and its parameters are evaluated
  • The object's super-class instance is intialized
  • The instance's instance initializers are executed and instance variables assigned in the order the initializers and variables are encountered in code
  • The constructor's body is executed.

  • So what happens is:
    1) The variable m is initialized to null first
    2) The instance initializer is executed first because it appears in code first
    3) The instance variable m is evaluated and assigned next
    4) The constructor is executed

    Campbell Ritchie

    Joined: Oct 13, 2005
    Posts: 44500
    It shows why it can be poor practice to mix initialisers and constructors. Unless, as you are doubtless doing here, using the following universal justification:-

    I just wanted to see what happens if …
    Consider Paul's rocket mass heater.
    subject: instance variable and initilization block : control flow
    It's not a secret anymore!