Sometimes in our java code we find that equality comparison operators(equals() and ==) do not work as expected.But why is that happening so? We know how they works .
Really?
Actually we don’t know in depth how they work.So in this java tutorial I am going to show how equals and == works and what is difference between them.So keep reading this java tutorial.
equals():
This method compares the actual content inside the object i.e two instances of a class having content with same meaning e.g
Integer num1=new Integer(10);
Integer num2=new Integer(10);
so num1.equals(num2) is true as obvious.
==:
== compares the references i.e the reference which is referring to the actual object not the content inside the object.Then if two references referring to the same object then references will be same. e.g
Integer num1=new Integer(1000);
Integer num2=num1; Now num2 is also referring to 1000
so num1==num2 is true.
Suppose if we say Integer num2=new Integer(1000); Now a new Integer object is created on the heap and its reference is assigned to num2.
so num1==num2 is false.
Now guess the output of
Integer n1=10; Integer n2=10;
if(n1==n2)
System.out.println(“same object”);
else
System.out.println(“Diff.object”);
Output is: same object
Yes that’s true;behaviour of == changes when boxing involves.This strange behaviour happens because JVM create the literal pool same as (String constant pool) for following wrapper objects (which must have been created through boxing)
- Boolean
- Byte
- Character range(\u0000 to \u007f)
- Short
- Integer range(-128 to 127)
So whenever you are creating such wrapper object then first it will be searched in it’s respective constant pool if it is found there it’s reference will be returned to new reference of wrapper object other wise it is created and stored in the pool.This strange thing happens just to save memory.
Thanks a lot.
ReplyDeleteIt helped me to understand the difference.......