File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Where is this line coming from??

 
Matt Player
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there, am kind of getting to grips with the whole (or a very, very small portion of) java thang but I have just typed in an example from my book which sounds a little like this;



and the output I get is this;

null says ruff!
last dogs name is Bart
Fred says ruff!
Marge says ruff!
Bart says ruff!


My question is, who is null and who invited him to the party?? Surely the last loop of the main body of code declares an integer, x and starts it at x=0 but myDogs[0].name = "Fred"

Any thoughts on this would be most welcome,

Cheers,

Matt.
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first thing you do in main() is:

You create a Dog (dog1) then tell it to bark. Bark looks like:

But when it gets called, name hasn't been assigned yet, so null gets printed out, and you get
"null says ruff!"
as the output.
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It comes from line 5 where you call the dog1's bark even before assigning a name to the dog1.
 
kannan vinayagam Duraiswamy
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you create an object, the class variables are initialized [name =null].

the class variable 'name' is first initialized with 'null'.
because in code there is no explicit initialization to the class variable 'name'.

then you call the 'bark()' behavior, in that the value of the name is 'null'.
So output is like
null says ruff!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic