This week's book giveaway is in the Cloud forum.
We're giving away four copies of The Business Blockchain and have William Mougayar on-line!
See this thread for details.
Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

programming query

 
paarul saxena
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
paarul saxena
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanxxx...for the help..that question did trouble me lot..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic