This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
Author

instance variable and initilization block : control flow

Vishwadeep Aggarwal
Greenhorn

Joined: Oct 30, 2012
Posts: 3


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
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

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


    Steve
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 38075
        
      22
    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
     
    Similar Threads
    Variable intializatio doubt
    Instance & static Initializers
    confusing statics!!!
    Initialization
    Compiles / Compiles but generate error??