GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes == and equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== and equals" Watch "== and equals" New topic
Author

== and equals

charu latha
Ranch Hand

Joined: Aug 20, 2002
Posts: 67
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

Joined: Aug 24, 2001
Posts: 348
per the code you posted, it runs without output anything
which means i==j is false.
charu latha
Ranch Hand

Joined: Aug 20, 2002
Posts: 67
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

Joined: Mar 18, 2004
Posts: 572
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
 
GeeCON Prague 2014
 
subject: == and equals