Signup/Sign In

Java Long equals() Method

Java equals() method belongs to the Long class. This method is used to compare the value of the Long 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 Long object is equal to the value of the parameter and returns false if the value of the Long 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 Long.

Returns:

It returns true if the value of Long object value is equal to the value passed as a parameter and returns false if the value of Long object value is not equal to the value passed as parameter.

Example 1:

Here the Long objects ob1, ob2, ob3 are checked for equality by using the equals() method.

public class StudyTonight 
{  
    public static void main(String[] args) 
    {          
        Long ob1 = 20L; 
        Long ob2 = 40L; 
        Long ob3 = 40L;  
          
        //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 number: ");  
            Long n1 = sc.nextLong();  
            System.out.print("Enter second number ");  
            Long n2 = sc.nextLong();  
            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 number: 67
Enter second number 54
Different numbers entered
*********************************
Enter first number: 99
Enter second number 99
Same numbers entered
*********************************
Enter first number: 98.66
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.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.