• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java initialization and creation  RSS feed

 
Arun Kumarr
Ranch Hand
Posts: 662
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we create a java object from a class, before even the static intializer block completes?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No objects of a class can exist before the class is loaded. Class loading involves running the static initializer, so the answer is no.
 
Arun Kumarr
Ranch Hand
Posts: 662
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason I ask this question is, in the following code I create an instance and call the method printMe(). It prints "printing me...". Then I deliberately throw an exception to fail the initialization. Just want to know what exactly happens here.




and



I get this output,

One - Static
One - Constructor
java.lang.ExceptionInInitializerError
at com.ge.java.One.testRun(Main.java:14)
at com.ge.java.One.<clinit>(Main.java:10)
at com.ge.java.Main.createOne(Main.java:43)
at com.ge.java.Main.main(Main.java:32)

printing me...
[ March 28, 2007: Message edited by: Arun Kumarr ]
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually class loading and class initialisation are separate steps. You can load a class without initialising it, with one of the Class.forName methods.

So by the time your static initialiser runs, the class is loaded, which means it's ready for instances to be created.

An ExceptionInInitializerError occurs when an exception happens in a static initialiser (including exceptions that happen on the right hand side of a static variable declaration statement). Static blocks cannot throw checked exceptions.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!