*
The moose likes Beginning Java and the fly likes Explanation needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Explanation needed" Watch "Explanation needed" New topic
Author

Explanation needed

vinodh kumar
Ranch Hand

Joined: Jan 07, 2008
Posts: 41
Hi,
Can any one explain me why the ouput is Goofy,it should be loofy na.


public class Dog {
String name;

public static void main(String[] args) {

Dog[] dog = new Dog[3];
dog[0]=new Dog();
dog[1]=new Dog();
dog[2]=dog[1];

dog[1].name="loofy";
dog[2].name="goofy";

System.out.println(dog[1].name);

}
}


VINODH KUMAR
/**SCJP 1.5***chemical engineering rocks*/ [My Wiki]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

dog[2] refers to the same Dog object as dog[1].


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3429
    
  12
This line
dog[2]=dog[1];
means dog[1] and dog[2] both refer to the same object, therefore any change you make to the object referenced by dog[2] will also be seen in the object referenced by dog[1].


Joanne
vinodh kumar
Ranch Hand

Joined: Jan 07, 2008
Posts: 41
Thanks a lot.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

You may have to go through this link for Pass by value, please!.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Explanation needed
 
Similar Threads
K & B - Generics & Collections
'void' type not allowed here
Learning about objects
How does Set identify duplicates(by == or equals)
how to accept an instance of a class as a parameter