This code sample is on page 261 of K n B. Output is ********************************* Hi Hi java.lang.NullPointerException ********************************** I am not getting how this output is coming. And I am unable to understand the meaning of Mixer m4=m3.m1; and Mixer m5=m2.m1;
what does it stand for >>>>reference variable.reference variable
A reference variable is a pointer to an object. When you have a statement like
what you are saying is access the object pointed at by the variable m3, get the value of that objects instance variable m1 and assign it to the reference variable m4.
The NullPointerException that is being reported in your program is due to the way that the object m2 is being instantiated. The Mixer class has 2 constructors. The m2 object is being instantiated with the no-args constructor - this means that its m1 instance variable is null.
Later when you attempt to set m5:
it is set to null. Next you try to run the go() method - this fails as m5 is null, hence the exception.
Hi Dinesh I also made few changes in program that reflects answer for you
class Mixer { Mixer() {} Mixer(Mixer m) { m1=m; } static Mixer m1=null; // line a public static void main(String[] arg) { Mixer m2=new Mixer(); Mixer m3=new Mixer(m2); m3.go(); Mixer m4=m3.m1; m4.go(); Mixer m5=m2.m1; go(); //line b System.out.println(m1==null); // line c System.out.println(m4==null); // line d } static void go() { System.out.println("Hi"); } }
Notice that i made m=null enev then we are able to call method go() that is static so it conclude that that we don't require class' instance to call static method. line b also clarify this. Regards Deepak