• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static initializer in Java  RSS feed

 
Abhay Bhatt
Ranch Hand
Posts: 64
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am very much interested in knowing the answer to the below Stack Exchange question:-

Stack Exchange Question

However, I think that in the below statement, Questioner meant removing keywords from the declaration of the variable, and not the 'static' keyword from the initialization block:-

If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.


But, the top answer, it seems, assumes the latter:-

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.


Also, the answer completely misses the case regarding removing the final keyword too!

I don't have enough privileges on Stack Exchange, so if anyone can answer it properly here, I'd really appreciate. Thanks!

 
Pete Letkeman
Ranch Foreman
Posts: 900
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, there are a couple of different things going on here, if I correct:
  • static initialization
  • instance initialization
  • final

  • Final variables can only be assigned a value once (often done when defining the variable).
    Instance initialization occurs any time a new object is created, common to have this happen when the "new" keyword is used. Instance methods or initialization can access static variables and static methods.
    Static initialization generally occurs when the program program starts. Static method or initialization cannot access instance variables or instance methods.
    Here is the code as originally posted with a main method for testing

    If you change

    by removing the final and the static initialization block

    then yes the program will compile. You do get different results with the if you are using static then if you are not using static.

    I'm unsure if I've answered your question.
    One thing that has been mentioned to me is, take the code, try to compile it and see what happens. Sometimes when you do this you can find out your answer right away without waiting on the forums to provide an answer. Please don't get me wrong, many people, including me, enjoy helping out and I'm not trying to turn you away by any means.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!