• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubts in Assignments

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

Can anyone please explain me the flow diagram for the code below.I am not able to understand why a null pointer exception is thrown at m5.go();
This one is from K &B Chapter 3 pg:261

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.println("Hi");
}
}
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If we take a look at the code closely the Mixer class has 2 constructors - one that takes an argument and one that doesn't.

The first Mixer object is instantiated using the no-args constructor:


The next Mixer object uses the constructor that takes an argument. When we pass m2 to the constructor it is stored in the m1 instance variable of the Mixer class.


The next line runs the go() method on m3.


The next line creates a new Mixer reference variable and assigns the value of m3.m1 to m4. Note that m3.m1 in this case points to the Mixer object m2 that we passed to the constructor above.


We now call the go() method on the m4 object.


We now create a new reference variable, m5, and assigns it the value of m2.m1. Note that when we create m2 we used the no-args constructor. Consequently the value of m1 is null in this case.


We now try to run the go() method on the m5 object. But the problem we have is that m5 is null and so we will get a NullPointerException.
 
sudhak
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Ian for the Detailed Explanation.I got it now
 
Is this the real life? Is this just fantasy? Is this a tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic