CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Oct 2011
    Posts
    13

    Question Why we use initialization block

    Hi to all,
    Hope you all will be fine. Actually i want to ask that we have a option to initialize variables in the constructor then why we use initialization block for it? Is there any efficiency issue in using initialization block?

    Like i used this code

    Code:
     /** Creates a new instance of EmailContent */
        public EmailContent() {
            
             
        } //end of constructor
    
     
        //Initialization Block
        // load the values for <h:selectOneMenu>
        {  
            emailEvents =  new ArrayList<SelectItem>();
            
            //The first item is a "no selection" item
            //new SelectItem(Object value, String label, String description, boolean disabled, boolean escape, boolean noSelectionOption)  )
            emailEvents.add(new SelectItem(null, "Pick a Email Event:", "", false, false, true));
            
            ArrayList returnedEmailEventGrid = (ArrayList)email_Event.getEmailEventGrid();
            
            //Check for Successfull completion
            if (Integer.parseInt(returnedEmailEventGrid.get(0).toString()) == 0) {
                
                for (int i = 1; i < returnedEmailEventGrid.size(); i++) {
                    
                    ArrayList returnRecord = (ArrayList) returnedEmailEventGrid.get(i);
                    
                    emailEvents.add(new SelectItem(returnRecord.get(0).toString(), returnRecord.get(1).toString()));
                      
                } //end of for()
                 
            } //end of if
              
        } //end of block
    But i can also do it in the constructor. like i make a method and call it from the constructor in which i write down the above code.

    Am i using initialization block right here or there is no need to use initialization block in my code?

    Thanks

  2. #2
    Join Date
    Feb 2008
    Posts
    966

    Re: Why we use initialization block

    The reason you would use initializers over the constructors is mainly useful for when you have final variables that may require programming logic to set them. Remember, a final variable MUST be set before the constructor is called, and the only way to do this is to set it to some static hard coded value, or to set it inside of an initializer block.

    If you want more information, I would suggest you read the Java specification located at http://java.sun.com/docs/books/jls/t...tion.html#12.4. They go into more detail there about the order in which initialization occurs.

  3. #3
    Join Date
    May 2009
    Posts
    2,413

    Re: Why we use initialization block

    Quote Originally Posted by Basit35 View Post
    Is there any efficiency issue in using initialization block?
    No there isn't. It's a design issue.

    You get a clean split between general intialization code and constructor specific initialization code.

  4. #4
    Join Date
    Feb 2008
    Posts
    966

    Re: Why we use initialization block

    why we use initialization block for it?
    One last thing I forgot to say: one of the main useful purposes of having the initializer blocks is so that the same code to initialize can happen no matter which constructor is called, without having to copy paste the code in each one, or create a separate method that is called by the constructor.

  5. #5
    Join Date
    Oct 2011
    Posts
    13

    Re: Why we use initialization block

    Hhmm thanks.
    I want to ask one thing more. Firts constructor runs, then initializer block? is it, Am i right?
    If static initializer block is present then first static initializer block run, then constructor and then non-static initializer block ? is it?

    Thanks.

  6. #6
    Join Date
    May 2009
    Posts
    2,413

    Re: Why we use initialization block

    Quote Originally Posted by Basit35 View Post
    Hhmm thanks.
    I want to ask one thing more. Firts constructor runs, then initializer block? is it, Am i right?
    If static initializer block is present then first static initializer block run, then constructor and then non-static initializer block ? is it?

    Thanks.
    No, all initialization blocks will run before any constructor. That's how initialization blocks help separate general initialization from constructor specific initialization I mentioned.

    But you shouldn't ask Java detail questions like this. Instead consult The Java Programming Language by Gosling and others. It's in the 4'th edition but a 5'th edition is due in the beginning of 2012. It's half a year away so I suggest you buy the 4'th edition used or borrow it. Every serious Java programmer needs this book.

    http://www.amazon.com/Java-Programmi...8932303&sr=1-2
    Last edited by nuzzle; October 18th, 2011 at 05:13 AM.

  7. #7
    Join Date
    Feb 2008
    Posts
    966

    Re: Why we use initialization block

    Actually Instance initialization blocks run inside of the constructor. They run after the explicit call to super(). When the code is compiled, the code in an initialization block is actually placed inside of each constructor after super() and before any other code.

    Straight from Java:

    The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
    http://download.oracle.com/javase/tu...O/initial.html

  8. #8
    Join Date
    May 2009
    Posts
    2,413

    Re: Why we use initialization block

    ---
    Last edited by nuzzle; October 18th, 2011 at 09:14 AM.

  9. #9
    Join Date
    May 2009
    Posts
    2,413

    Re: Why we use initialization block

    Quote Originally Posted by ProgramThis View Post
    Straight from Java:
    Note that Java is defined by its standard (with the book I mentioned as official interpretation).

    I find the statement you refer to misleading. What a compiler does or doesn't isn't part of the Java language unless the standard says so. The book I mention has a more accurate description (in 2.5.2 Initialization Blocks),

    "It is executed as if it were placed at the beginning of every constructor in the class"

    The same sourse states about static initializers (2.5.2 Static Initialization):

    "The static initializers are executed after a class is loaded before it is actually used"

  10. #10
    Join Date
    Feb 2008
    Posts
    966

    Re: Why we use initialization block

    So what you are saying is that a comment in a book you read is more accurate than the documentation listed on oracle.com?

    What is misleading about the statement? It doesn't execute "as if it was placed at the beginning" it IS placed at the beginning. Your statement (taken from the book, granted) is more misleading IMHO because it says "as if" when in actuality it "is" placed right after the call to super().

    "The static initializers are executed after a class is loaded before it is actually used"
    Okay, so? What does this have to do with the conversation at hand? It says the same thing pretty much in the specification:
    12.1.2 Link Test: Verify, Prepare, (Optionally) Resolve

    After Test is loaded, it must be initialized before main can be invoked.

  11. #11
    Join Date
    May 2009
    Posts
    2,413

    Re: Why we use initialization block

    Quote Originally Posted by ProgramThis View Post
    So what you are saying is that a comment in a book you read is more accurate than the documentation listed on oracle.com?
    That's right. What you read at oracle.com is not "Java". Java is defined by the Java Language Specification and in addition there's a more easily digestable official interpretation of that specification, namely The Java Programming Language. Everything else is basically heresay and should be treated with suspicion.

    This is a confusing and misleading statement,

    "The Java compiler copies initializer blocks into every constructor"

    What compiler? The Oracle compiler? There's no "THE Java compiler". As I said, Java is defined by a standard specification, not by some compiler. If the standard says this is what the compiler should do then the statement is correct but the standard doesn't state that. The above statement appearantly has mislead you into thinking that the Java standard stipulates that the initialization block must be copied into the constructor (*). And now you're spreading your misunderstanding at this forum.

    Finally I posted information about static initializers because the OP mentioned them (in #5). Note that if you refer to the standard make sure to quote the proper section. How a Java program behaves at start has little to do with static initializers.

    (*) At least I cannot find anything to that effect.
    Last edited by nuzzle; October 19th, 2011 at 10:57 PM.

  12. #12
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Why we use initialization block

    Quote Originally Posted by ProgramThis
    So what you are saying is that a comment in a book you read is more accurate than the documentation listed on oracle.com?
    It's not a matter of one being right and the other being wrong. The difference between the two is the Java Language Specification defines what must happen but not how it must be implemented whereas Oracle's site is stating how Oracle's (Sun's) version of Java implements the spec's requirement.
    Last edited by keang; October 19th, 2011 at 04:20 AM.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured