• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
  • Carey Brown
  • salvin francis
  • Piet Souris

Null Pointer Exception: constructors dilemma

Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was just going through java questions in Facebook group for Java and found below code throwing null pointer Exception. I gave an explanation below. However i want to make sure i have given correct explaination. So please review it and let me know so that i can convey the same

can anyone explain
why jvm throw NullPointerException?

My Explaination:

That is because you are recraeting instance of class A and this is not set to reference of A in class B. here is the flow of your program
1. Created instance of A in main()
2. call m1();
3. Inside m1(), created instance of Class B.
4. call m2(CURRENT instance of A)
5. set this insatnce of A to A's reference valraible a
6. Sysout and exit m2.
7. sysut in m1() and exit m1() and come back to main method
8. Create instance of B( which calls uper class constructoer and create new instance of A)
9. call m3();
10. Now m3 dont have instance of A set in a, a is null, so throw Null Pointer Exception.
11. Now how do we solve it: just call m3 with refernce var a holding instanceof A actualy,
This can be done by calling m3("msg") from m2(); and comment b.m3("prince") from main method or pass instance of A to m3() and set it to ref variable a in m3() body

Changes req any one of below:
1. comment b.m3("prince"); in main() and call from m2();
2. pass instance of A to m3() ns et it there to a e.g
b.m3("prince", newA());

Just want to make sure my explaination is correct.
Ruth Stout was famous for gardening naked. Just like this tiny ad:
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic