Quote
I understand that the relational operator "==" is primarily used to check the equivalence of primitive types, something like :
int x = 5; int x2 = 5; System.out.print(x == x2)
This would return true in this case.
However, if I set up something like this:
class Value
{
}
public class TestForEquivalence
{
public static void main(String [] args)
{
// Test #1 - Use equals() method to test object references
Value v1 = new Value();
Value v2 = new Value();
System.out.println("v1.equals(v2): " + v1.equals(v2));
// Test #2 - Use relational operator "==" to test object references
System.out.print("v1 == v2: ");
System.out.println(v1 == v2);
In test #1, I use the inherited equals() method of class Object to test my two object references v1 and v2. But, in test #2, I can also use the "==" operator to do the same thing.
So my question is, is there a difference between using equals() or "==" to test object references?
P.S - I am also aware that most of the Java standard classes will override equals() so that it will compare object contents. Example below:
// Test #3 - Using overridden equals() method in class Integer to test object CONTENTS
Integer n1 = new Integer(50);
Integer n2 = new Integer(50);
System.out.println("n1.equals(n2): " + n1.equals(n2));
Result will be true in this case.
API : equals() method of class Integer.
Hope this makes sense. Thanks in advance

New Topic/Question
Reply




MultiQuote





|