Monday, March 8, 2021

Java equals method and '==' operator

Compare Object value : 

If we want to compare two object value like two Long or Integer value then we must need to use equals method instead of  operator '=='.

Operator  '==' compares reference and not value. But some times this creates an illusion that operator comparing the value. See below example

example: 1

Long l1= 127L;

Long l2=127L;

System.out.println(l1==l2) ///  This will return true;

System.out.println(l1.equals(l2)); ///  This will return true;

But if you give some higher value like;

example: 2

Long l1= 128L;

Long l2=128L;

System.out.println(l1==l2) ///  This will return false;

System.out.println(l1.equals(l2)); ///  This will return true;

example:1 prints true because java maintain Long constant pool for range between -128 to 127.

And when you compared the values above to constant pool range then it given false.

We can compare primitive value using operator '==' but should not be used for object.


Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home