aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explain output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "explain output" Watch "explain output" New topic
Author

explain output

srinivas sridaragaddi
Ranch Hand

Joined: Jul 24, 2007
Posts: 225
hi,

i am confused with the output so please explain what is happening here

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();//line 1
void go() { System.out.print("hi "); }
}

Nullpointer exception because of line 1

Thanks


SCJP 5.0<br /> <br />"Skills are started with learning and mastered with improvement. Nothing is hereditary except death" BUDDHA...
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
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();//line 1
void go() { System.out.print("hi "); }
}

Hi,
Here we are having a Mixer class with default constructor, with an argument constructor and a reference variable of type Mixer(i.e m1). so any object we will create for this class will have one instace variable m1 for that object. Below makes it clear-:

Mixer m2 = new Mixer();
will run the default constructor and make an object. This object will be having its instnce variable m1 which can refer to an object of type Mixer.

Mixer m3 = new Mixer(m2); m3.go();
will run the argumented constructor and will assign m3's instance variable m1 the reference to what m2 is referencing. So m3 object's instance variable m1 will point to the object m2 is pointing, and will print "hi" if all goes well.

Mixer m4 = m3.m1; m4.go();
due to this m4 will refer to what m3's m1 variable is reffering to i.e the object m2 is refering to.and will print "hi" if all goes well.

Mixer m5 = m2.m1; m5.go();//line 1
Here m5 will refer to what m2's m1 variable is reffering to, but its not reffering to any Mixer object so will throw a null pointer exception.

thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explain output