File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes output not clear Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "output not clear" Watch "output not clear" New topic

output not clear

rakhee gupta
Ranch Hand

Joined: May 01, 2008
Posts: 43
Hi ,
I was checking this code

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 "); }
What is the result?
A. hi
B. hi hi
C. hi hi hi
D. Compilation fails
E. hi, followed by an exception
F. hi hi, followed by an exception

The answer to this is F.And the explanation goes in K&B is 'The m2 object's m1 instance variable is never initialized, so when m5 tries to use it a
NullPointerException is thrown.'

This is not clear.
Ashish Hareet
Ranch Hand

Joined: Jul 14, 2001
Posts: 375

Lets iterate over what happens when main is called

Mixer m2 = new Mixer(); //m2 references a new instance of Mixer, instance variable m1 is not initialized since the no-args constructor is called

Mixer m3 = new Mixer(m2); ///m3 references a new instance of Mixer, instance variable m1(in the new instance) references m2

m3.go(); //prints "hi "

Mixer m4 = m3.m1; //m3 references an instance of Mixer previously created(m2)

m4.go(); //essentially m2.go() since m4 references m2 from the previous assignment, prints "hi "

Mixer m5 = m2.m1; //m5 references the instance variable m1 in m2, note from above that m2 was created using the no-args constructor & instance variable m1 in m2 never got initialized.

m5.go(); //since m5 is a null reference, a NullPointerException is thrown

if we'd created m2 as such "Mixer m2 = new Mixer(new Mixer());" then m2.m1 will refer to an instance of Mixer, "Mixer m5 = m2.m1" will also refer to the same instance & we'll not get a NullPointerException

Ashish Hareet
[ June 17, 2008: Message edited by: Ashish Hareet ]
I agree. Here's the link:
subject: output not clear
jQuery in Action, 3rd edition