• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

output not clear

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
I was checking this code

Given:
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.
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rakhee,

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


HTH
Ashish Hareet
[ June 17, 2008: Message edited by: Ashish Hareet ]
 
roses are red, violets are blue. Some poems rhyme and some are a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic