wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explain me this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "explain me this code" Watch "explain me this code" New topic
Author

explain me this code

anamika henry
Ranch Hand

Joined: Mar 09, 2007
Posts: 30
class Mixer{
Mixer(){}
Mixer(Mixer m){m1=m;}
Mixer m1;
public static void main(String[] args){
Mixer m2= new Mixer();
Mixer m3 = new Mixer(m2); m3.go();
Mixer m4= m3.m1; m4.go();
Mixer m5 = m2.m1; m5.go();

}
void go() {System.out.print("hi");}
}
Abdullah Mamun
Ranch Hand

Joined: Mar 19, 2007
Posts: 99

This will throw NullPointerException because of the line m5.go();

May I ask, what actually you want to know?


MooN
anamika henry
Ranch Hand

Joined: Mar 09, 2007
Posts: 30
can you explain me the line

Mixer m5 = m2.m1; m5.go();

what is m2.m1 and m5.go(); means
Abdullah Mamun
Ranch Hand

Joined: Mar 19, 2007
Posts: 99

First, lets have a look at the Mixer class. It has one instance variable m1 of type Mixer and go() method.



In line 4, m2 is a mixer object created at line 1 and that time m1 is initialized with null. Since m1 is also a Mixer, it can be assigned in m5 but as m1 is null m5 is also null. So, when you are calling the go() method on a null object(m5) JVM is giving a NullPointerException.

Hope, I could make you understand...
anamika henry
Ranch Hand

Joined: Mar 09, 2007
Posts: 30
thank you moon, i could understand now
tirapa reddy
Greenhorn

Joined: May 05, 2007
Posts: 19
hi
m1 is assigned with m how it becomes null ?
David Grant
Greenhorn

Joined: Apr 01, 2008
Posts: 13
m1 is instantiated using the no-arg constructor, Mixer(), which leaves the m instance variable unchanged from its initial value of null.
Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
yes it will throw a null pointer exception..


SCJP 1.4 - 95% [ My Story ] - SCWCD 1.4 - 91% [ My Story ]
Performance is a compulsion, not a option, if my existence is to be justified.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: explain me this code
 
Similar Threads
explain output
Please Explain
K & B question ???
Exception
Clarification on Q6 Self-Test Chapter 3 K&B SCJP5