LAST UPDATED: AUGUST 26, 2020
Java Double equals() method
Java equals()
method belongs to the Double
class. This method is used to compare the value of the Double-object currently used with the value of the parameter. It has boolean as its return type i.e returns true
if the value of the Double-object is equal to the value of the parameter and returns false
if the value of the Double-object is not equal to the value of the parameter.
This method overrides the equals()
method of Object
class.
Syntax:
public boolean equals(Object obj)
Parameter:
The parameter passed is the Object which is to be checked for equality with the Double-object.
Returns:
Returns true
if the value of Double-object value is equal to the value passed as a parameter and returns false
if the value of Double-object value is not equal to the value passed as parameter.
Example 1:
Here, the Double objects ob1, ob2, ob3 are checked for equality by using the equals() method.
import java.lang.Double;
public class StudyTonight
{
public static void main(String[] args)
{
Double ob1 = 20.0;
Double ob2 = 40.0;
Double ob3 = 40.0;
//Checking for objects with equal and unequal values
System.out.println("ob1 and ob2 equal? "+ob1.equals(ob2));
System.out.println("ob2 and ob3 equal? "+ob2.equals(ob3));
}
}
ob1 and ob2 equal? false
ob2 and ob3 equal? true
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the desired result.
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first double value: ");
Double n1 = sc.nextDouble();
System.out.print("Enter second double value ");
Double n2 = sc.nextDouble();
boolean r = n1.equals(n2);
if (r==true)
{
System.out.println("Same numbers entered");
}
else
{
System.out.println("Different numbers entered");
}
}
catch(Exception e)
{
System.out.println("Invalid input!!Please check");
}
}
}
Enter first double value: 88.66
Enter second double value 88.66
Same numbers entered
****************************************
Enter first double value: 98.99
Enter second double value 98.998
Different numbers entered
****************************************
Enter first double value: 0x88.8
Invalid input!!Please check
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.