Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Statics doubt?  RSS feed

 
rizwana mujawar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please correct me if iam wrong....
All Static members i.e,methods & variables are compiled and run by the compiler itself as soon as the class is loaded by the compiler....
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rizwana mujawar wrote:Please correct me if iam wrong....
All Static members i.e,methods & variables are compiled and run by the compiler itself as soon as the class is loaded by the compiler....


Sorry, but no.

  • Variables aren't "run."
  • Nothing is run by the compiler. It's run by the JVM.
  • Methods are never run until we call them.


  • The keyword "static" simply means "associated with the class as a whole, rather than with individual instances."
     
    William P O'Sullivan
    Ranch Hand
    Posts: 859
    Chrome IBM DB2 Java
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When a Class is instantiated, all static initializers are executed first, then the constructor (if present).

    I like to ask this question in interviews! ;)

    WP
     
    Jeff Verdegan
    Bartender
    Posts: 6109
    6
    Android IntelliJ IDE Java
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    William P O'Sullivan wrote:When a Class is instantiated, all static initializers are executed first, then the constructor (if present).


    Not quite.

    Static initializers are run once, when the class is initialized (which is a separate step from when it's loaded, but for most purposes can be thought of as part of the loading process).

    Instance initializers are run once for each instance created, before that class's constructor (but after the parent's instance initializers and c'tor).

    And a constructor is always present.

    </pedant>
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!