= = Operator and equals method:
- When the state of two objects are equal then we can say those two classes are equal. We can check equality in two ways i.e.,
- == operator
- == is a Relational operator. It checks the memory location of the object
In the above example we create two instances for different Student classes i.e., s1 & s2 are the instances of those classes. These two instances are referring different objects i.e., address locations are different s1 is pointing 1000 location and s2 is pointing to 1001 location so addresses are different. Here we check the condition like s1 == s2 if it is True it gives output as Equal otherwise it gives Not Equal. That means if the instances are referring same address location it gives Equal otherwise Not Equal.
- == is mostly used for primitive data types not for Objects.
- Always it comparing the Two values these Two values should be same type.
In the above example r1 & r2 are two instances of that class r1 is pointing to 1200 address location and r2 is pointing to 1201 address location after that r1 is also pointing to r2 address location only. After that we check the condition if the two are referring same address location so it gives “They are equal.”Ex:3:
In the above example s1,s2 are the two variables and we are initializing values for that variables like s1=13,s2=13.Then it checks s1==s2 it gives an output as “Equal” because here the values are comparedequals():
The equals method checks the values, see the above example, there we are creating two instances of string with the name “geek” and “geek” , the equal method check the values which are in String object state(object state is nothing but values of object). When we use ” ==” instead of “equals” it gets printed “not equal” because the two instances pointing two different locations, the ” ==” not checks the actual value, it checks the address of a location