32 What’s the purpose of equal method?

What’s the purpose of equal method?

In Java, equal method is used to compare two object based on some specific condition like the value of field.

Example:
ObjectComparisonExample.java

public class ObjectComparisonExample  

{  

public static void main(String[] args)   

{  

//creating constructor of the Double class   

Double x = new Double(123.45555);  

//creating constructor of the Long class   

Long y = new Long(9887544);  

//invoking the equals() method   

System.out.println(“Objects are not equal, hence it returns “ + x.equals(y));  

System.out.println(“Objects are equal, hence it returns “ + x.equals(123.45555));  

}  

}  

Output

Area of rectangle: 6.0
Area of circle: 12.56

Note: If you compare by == operator, it compares reference variable, not compare the value.

 

Leave a Reply

Your email address will not be published. Required fields are marked *