This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ExceptionInInitializerError in inner classes

 
Monalisa Das
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


the output is ExceptionInInitializerError caused by java.lang.NullPointerException..
Why the code didn't worked out well?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what happens:

- When class I is loaded, it is initialized, which means its static member variables are initialized: so, the static member i on line 3 is initialized.
- To initialize i, a new instance of I is created.
- To initialize that new instance of I, an instance of J is created (line 4).
- However, when line 4 is executed, i is still null (because the whole reason line 4 is executed, is because we're initializing the static member i - which isn't done yet).
- When you do i.new J(); when i is null, you get a NullPointerException.
- That gets wrapped in an ExceptionInInitializerError, because that's the kind of error that is thrown when something goes wrong while initializing a class that has just been loaded (remember, this all started with the initialization of class I).
 
Gaurav. Prasad
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because static cannot evaluate the initialize I i .
 
Monalisa Das
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:This is what happens:

- When class I is loaded, it is initialized, which means its static member variables are initialized: so, the static member i on line 3 is initialized.
- To initialize i, a new instance of I is created.
- To initialize that new instance of I, an instance of J is created (line 4).
- However, when line 4 is executed, i is still null (because the whole reason line 4 is executed, is because we're initializing the static member i - which isn't done yet).
- When you do i.new J(); when i is null, you get a NullPointerException.
- That gets wrapped in an ExceptionInInitializerError, because that's the kind of error that is thrown when something goes wrong while initializing a class that has just been loaded (remember, this all started with the initialization of class I).


Thanks a lot sir.. the reason was simple but was not clicking in my mind...once again thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic