-3

I know that to make an object unique in Java, I have to implement the hashcode() and equals() methods.

But why are these two objects different when we create two objects from a class?

public class ClassA {

    public static void main(String []arg) {

        ClassA classa = new ClassA();
        ClassA classb = new ClassA();

        //here classa and classb are not equal. Why?
        if(classa == classb) //returns false

    }    
}
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
pankaj lal
  • 25
  • 4
  • Because `new` creates a... new object. – Maroun Nov 13 '16 at 14:25
  • Compare them with the method `equals()`. – Nikolas Charalambidis Nov 13 '16 at 14:25
  • @Maroun No I like to know why. if we create same class two objects why?? – pankaj lal Nov 13 '16 at 14:27
  • Don't compare reference types using `==` or `!=`. Use the `equals(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The equals method on the other hand checks if the two references are *functionally equivalent*, and that's what matters here. – Hovercraft Full Of Eels Nov 13 '16 at 14:29
  • `"No I like to know why."` -- please understand that this has been asked and answered many times on this site ([for example](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+reference+object+equals+vs+%3D%3D)). If you feel that yours is adding something new or different, then you should show the fruits of your research and tell why your question is different from all the others. If you've not yet put in this key effort to do a decent search before asking your question, then perhaps you're asking this question prematurely. – Hovercraft Full Of Eels Nov 13 '16 at 14:36

1 Answers1

0

== operator checks memory addresses of the objects. classa and classb are different objects, they have different memory addresses, therefore classa==classb returns false.

mtyurt
  • 3,369
  • 6
  • 38
  • 57