File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Junior/Associate Certification (SCJA,OCAJ 5/6/8) and the fly likes programming query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Junior/Associate Certification (SCJA,OCAJ 5/6/8)
Bookmark "programming query" Watch "programming query" New topic

programming query

paarul saxena

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();"aiko";"aiko";
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
paarul saxena

Joined: Jun 18, 2008
Posts: 10
thanxxx...for the help..that question did trouble me lot..
I agree. Here's the link:
subject: programming query
It's not a secret anymore!