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?
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
Just want to make sure my explaination is correct.