Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help needed

 
Allan Tan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the following code prints "Not Equal"?
How does equals perform comparison?
public class Test
{
public static void main(String args[]) {
Long L = new Long(7);
Integer J = new Integer(7);
if (L.equals(J)) System.out.println("Equal");
else System.out.println(" Not Equal");
}
}
 
nachiket deshpande
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(obj1.equals(obj2)) method checks whether the two objects(obj1 and obj2) belongs to the same class.if they belong to the same class they are equal else not.since L and I belong to two different classes(Long and Integer),the answer answer is not equal.hope this helps.
 
Michael Hildner
Ranch Hand
Posts: 297
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the API says for that method:
Compares this object against the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object.
This will print out 'true' though:
System.out.println(L.longValue() == J.longValue());
 
Allan Tan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic