In this Java tutorial, you will learn about Integer.equals() method, and how to use this method to check if two Integer objects are equal in value, with the help of examples.

Integer.equals()

Integer.equals() compares this integer object to the argument. If both the objects have same integer value, then equals() returns true, else it returns false.

Syntax

The syntax of equals() method is

</>
Copy
Integer.equals(Object obj)

where

ParameterDescription
objThe other object with which we compare this Integer object to.

Note: The argument you pass can be of any type. You pass int, float, double, etc.

Returns

The method returns value of type boolean.

Examples

1. Integer.equals() when both the integers are equal in value

In this example, we will take two integer objects: integer1 and integer2 such that their int values are same. We will check if integer1 equals integer2 using Integer.equals() method. Since, both the objects are same in their value, equals() returns true.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		Integer integer1 = 7;
		Integer integer2 = 7;
		boolean result = integer1.equals(integer2);
		System.out.println("Result of equals() = " + result);
	}
}

Output

Result of equals() = true

2. Integer.equals() when the integers are not equal in value

In this example, we will take two integer objects: integer1 and integer2 such that their int values are not same. We will check if integer1 equals integer2 using Integer.equals() method. Since, both the objects are not same in their value, equals() returns false.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		Integer integer1 = 7;
		Integer integer2 = 8;
		boolean result = integer1.equals(integer2);
		System.out.println("Result of equals() = " + result);
	}
}

Output

Result of equals() = false

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Integer.equals() method, and also how to use this method with the help of Java example programs.