File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Where is this line coming from?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Where is this line coming from??" Watch "Where is this line coming from??" New topic

Where is this line coming from??

Matt Player

Joined: Jan 11, 2009
Posts: 11
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,


Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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

Joined: Oct 18, 2004
Posts: 136

It comes from line 5 where you call the dog1's bark even before assigning a name to the dog1.

SCJP 5.0 and now fighting with ExtJS
kannan vinayagam Duraiswamy
Ranch Hand

Joined: Jan 12, 2009
Posts: 52
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!

I agree. Here's the link:
subject: Where is this line coming from??
It's not a secret anymore!