Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explain me this code

 
anamika henry
Ranch Hand
Posts: 30
  • 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();

}
void go() {System.out.print("hi");}
}
 
Abdullah Mamun
Ranch Hand
Posts: 99
Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This will throw NullPointerException because of the line m5.go();

May I ask, what actually you want to know?
 
anamika henry
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you explain me the line

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

what is m2.m1 and m5.go(); means
 
Abdullah Mamun
Ranch Hand
Posts: 99
Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you moon, i could understand now
 
tirapa reddy
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
m1 is assigned with m how it becomes null ?
 
David Grant
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes it will throw a null pointer exception..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic