Integer Equals() method in Java

Java 8Object Oriented ProgrammingProgramming

The Equals() method compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

Let us first set Integer object.

Integer val1 = new Integer(30);
Integer val2 = new Integer(60);
Integer val3 = new Integer(55);
Integer val4 = new Integer(30);

Now let us check their equality using the Equals() method.

val1.equals(val2);

In the same way, check it for different Integers.

Let us see the complete example.

Example

 Live Demo

import java.util.Random;
public class Demo {
   public static void main( String args[] ) {
      Integer val1 = new Integer(30);
      Integer val2 = new Integer(60);
      Integer val3 = new Integer(55);
      Integer val4 = new Integer(30);
      System.out.println("Integer 1 = "+val1);
      System.out.println("Integer 2 = "+val2);
      System.out.println("Integer 3 = "+val3);
      System.out.println("Integer 4 = "+val4);
      System.out.println(val1.equals(val2));
      System.out.println(val1.equals(val3));
      System.out.println(val1.equals(val4));
   }
}

Output

Integer 1 = 30
Integer 2 = 60
Integer 3 = 55
Integer 4 = 30
false
false
true
raja
Published on 13-Nov-2018 05:36:40
Advertisements