LAST UPDATED: AUGUST 25, 2020
Java Integer equals() Method
Java equals()
Method belongs to the Integer
class. This method is used to compare the value of the Integer 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 Integer object is equal to the value of the parameter and returns false if the value of Integer 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 Integer.
Returns:
returns true
if the value of Integer object value is equal to the value passed as a parameter and returns false
if the value of Integer object value is not equal to the value passed as parameter.
Example 1:
Here the Integer objects ob1,ob2,ob3 are checked for equality.
public class StudyTonight
{
public static void main(String[] args)
{
Integer ob1 = 20;
Integer ob2 = 40;
Integer ob3 = 40;
//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 integer: ");
Integer n1 = sc.nextInt();
System.out.print("Enter second integer ");
Integer n2 = sc.nextInt();
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 integer: 78
Enter second integer 23
Different numbers entered
**********************************
Enter first integer: 89
Enter second integer 89
Same numbers entered
**********************************
Enter first integer: 0x009
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.