Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loading and Initializing

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Loading means when a class is loaded. So in this case when java.io.* and java.custom.* are imported in the class, does that mean loading ? int num=20 is initializing of num

If there is s static initializer block in this code or in java.Custom, will it be executed immediately with loading of class (ie on import of class) ?
If I want to test, how can I test this ? If I want to load the class, then I will have to run this code as "java TestLoading" , and it will execute main(). So even if a static initializer block runs on loading, I will not be able to know that. Is there a way, I wan stop execution of code after loading ? Or is there a way I can just run class upto loading and not any further ?

Thanks
 
Ivan Jozsef Balazs
Rancher
Posts: 979
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So in this case when java.io.* and java.custom.* are imported in the class,


The import statements are evaluated at compile time, and in the class file the classes are referred by by full package + class names.

If there is s static initializer block in this code or in java.Custom


I see no static initializer block in this class. It would look like this



This non-static initializer is executed along with every constructor.

You provided no constructor, so the compiler inserted a default one:
one without arguments and performing super().

If you write another class, and do something like this in its main method,

and let that class run, then the TestLoading class will be loaded and initialized, and the an instance will be created and returnInt exevcuted.

You might want to insert System.out.println calls into the methods you want to track.

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Import do not means class is loaded. Class is loaded dynamically in JVM when it is used first time.

Consider below mentioned code






above mentioned Tester class , when executed, do not print anything which show that just importing a class (TestA in our case) will not load the class in JVM.

Let us modify Tester class now ..



now above code shall print two lines. This means that now since class TestA is used to called it's method, TestA class is loaded in JVM by classloader thereby calling static block.



 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic