Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Basic Java

 
harish marathi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a problem with static keyword
given a condition where
a)static block
b)static method
c)static variable
d)public static void main(String args[])
exists in a program.
What is the order of precedence of invocation ?
help
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is not really an IO and Streams question, so I've moved it to Java in General (beginner) for you.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not sure what you mean by "invocation" in this context... I believe you mean "which exists first, and in what order do they get called"...

Basically all these things "exist" at the same time... when the JVM loads up the class, they are all created before you can access the class in any way.

The static block is executed whenever you first make any reference to the class it is in... create an object of the class? The static block is executed. Call a static method, or access a static variable? The static block is executed. Run a java class that has a static block? The static block is executed before main() begins.

However, in the static block, you can access static methods and variables, so you can technically think of them existing before the static block, but in reality, all these things "start existing" at the same time...

Technically, static methods ( Technically, the main() method falls into this category too... it is just a special case of a static method. ) are only invoked when you invoke them... the only exception to this is main()... the JVM knows that main() is the starting point of execution in a program...

Here is some code that may illustrate these concepts better than I have been at explaining them...








Try running StaticClass first, and then StaticClassTest and see the difference in output... hopefully this will help you see what is going on...

HTH,
-Nate
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic