Two Laptop Bag*
The moose likes Associate Certification (SCJA,OCAJ 5/6) and the fly likes programming query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Associate Certification (SCJA,OCAJ 5/6)
Bookmark "programming query" Watch "programming query" New topic
Author

programming query

paarul saxena
Greenhorn

Joined: Jun 18, 2008
Posts: 10
i hava a trouble with a few programming questions...would be grateful if someone helps out..
supposedly a program construct creates two new instances as given below:
class Dog{
String name;
public static void main(Sting []args){
Dog d1=new Dog();
Dog d2=new Dog();
d1.name="aiko";
d2.name="aiko";
if(d1.equalsd(2))
System.out.println("true");
}
}
why no output is produced when according to mackenzie book it gives true??
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
First of all your program will give you compier error at two places as typed:

1. You have typed Sting instead of String in the main method.
2. The correct implementation of equals method would be d1.equals(d2). You have typed it in some other way, probably the paranthesis are not correctly placed.

Having said that, even if you correct the above errors, the code will not print anything because the equals method checks whether the two references refer to the same object or not. Here d1 and d2 are references to two different objects, though their name attribute is same. Hence d1 is not equal to d2. If you run d1==d2, it will return false. Equals method works like == only. If you want that it should compare the name attribute of the dog object and then return the result, you would have to override the equals method of the object class. To do that you use the following code:

If you want to learn more about equals, read this

String class has appropriately over-ridden the equals method that is why we are able to compare two name attributes, though they are two different String objects.
[ August 21, 2008: Message edited by: Anand Shrivastava ]

Anand Shrivastava
SCJA
paarul saxena
Greenhorn

Joined: Jun 18, 2008
Posts: 10
thanxxx...for the help..that question did trouble me lot..
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: programming query