• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explain output

 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pranav Bhatt
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic