• Post Reply Bookmark Topic Watch Topic
  • New Topic

static initializer blocks in class  RSS feed

 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when do they get called?

from my code


i did get the "initializing..." string output, even though i didn't create any MyJava objects.
from this fact, i inferred that initializing blocks get called once when the program compiles.

am i right?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, not when the program compiles.

Compiling means: translating the source code (*.java) to a *.class file. You do this with the Java compiler (javac). You do this only once, and then you have your executable program in the form of one or more *.class files. No code of your program is executed at compile-time.

You can then run the program. Static initializers are executed when the class is loaded; in your case, when the Java Virtual Machine loads the MyJava class.
 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so when i type

java MyJava

in cmd.exe, not

javac MyJava.java, right?
thanks


 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

You compile your code with javac, the Java compiler.

You run the code with java, the Java application launcher.

This page from Oracle's tutorials explains the steps: About the Java Technology
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abigail Decan wrote:when do they get called?

Abigail,

I don't want to dampen your enthusiasm, but could I suggest that you actually read through whole chapters of the tutorials (or do a little bit of research) before firing off questions? Right now, it has the feeling that you're posting as soon as you see something that "does not compute", where a little further reading (or a search of this website; or indeed Google) might well answer your question.

It's great that you're learning, and we're happy to help; but we don't generally like the feeling of being "machine-gunned".

Thanks

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!