This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== and equals

 
charu latha
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Equalsoperator {
public static void main(String args[]) {
Integer i = new Integer(5);
Integer j = new Integer(5);
if (i==j)
System.out.println ("True");
}
}
The above code prints true irrespective of whether i use the == operator or the equals method. Why is this?
I thought the operator "==" was supposed to do a comparision of the references and the equals method was supposed to do a comparision of the values. Is my assumption wrong?
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
per the code you posted, it runs without output anything
which means i==j is false.
 
charu latha
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this one. Let me explain. Yes it will not print anything because when we use the "new" operator this creates a new object in memory. So if i used the equals operator (==) then this would do a reference comparision and since the references point to different objects it would not print anything. Alternately if i had used the equals method (equals()) this would have printed true.
I hope i am right in my explanation. Correct me if i am wrong.
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you are right
The only two operators that can be used with object references are comparing for equality (==) and inequality (!=). These operators compare two values to see if they refer to the same object. Although this comparison is very fast, it is often not what you want.
Many times you want to know if the objects have the same value, and not whether two objects are a reference to the same object. For example,
if (name == "Mickey Mouse") ...
will be true if name is a reference to the same object that "Mickey Mouse" refers to. However, this will probably be false if the String in name was read from input or computed (by putting strings together or taking the substring), even though name really does have exactly those characters in it.
Many classes (eg, String) provide a version of the equals() method to compare the values of objects
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic