-2

Hello and happy new year folks.

I am new at JAVA. I have written a code as below. When I run it I get following output.


1 and 2 are same

1 and 2 are equal


Why can't I get same output for the other if statements? All 3 objects (example1, example2 and example3) is derived from class 'Test'. All 3 are from same origin, class 'Test'. So not only 1vs 2 but also 1 vs 3 and 2 vs 3 should be same/equal.

Any idea please.?

MY CODE IS HERE:

public class Test {
    
    public static void main(String[] args) {
        
        Test example1 = new Test();
        Test example2 = example1;
        Test example3=new Test();
        
        if (example1==example2){
            System.out.println("1 and 2 are same");
        }
        
        if (example1==example3){
            System.out.println("1 and 3 are same");
        }
        
        if (example2==example3){
            System.out.println("2 and 3 are same");
        }
        
        if (example1.equals(example2)){
            System.out.println("1 and 2 are equal");
        }
        
        if (example1.equals(example3)){
            System.out.println("1 and 3 are equal");
        }
        
        if (example2.equals(example3)){
            System.out.println("2 and 3 are equal");
        }
        
    }
}

Pavlus
  • 1,651
  • 1
  • 13
  • 24
ucanbizon
  • 37
  • 1
  • 7
  • You are comparing references. – Spectric Dec 31 '20 at 14:53
  • Check this post [Compare with == or equals](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839). The post explains the same concept but with Strings – Andres Sacco Dec 31 '20 at 14:54

1 Answers1

2

== evaluates pointer equality when referring to Java objects. Your two pointers example1 and example2 point to the same object, so they are equal, while example1 and example3 point to different objects, so they are not equal.

.equals() by default exhibits the same behavior, and compares memory addresses. You can override the method in your Test class to make it more intelligently compare your objects, but out of the box all it can do is essentially run ==. String is an example of a class with a custom implementation of .equals().

Liftoff
  • 24,717
  • 13
  • 66
  • 119