Check two numbers for equality in Java

Java 8Object Oriented ProgrammingProgramming

To check two numbers for equality in Java, we can use the Equals() method as well as the == operator.

Firstly, let us set Integers.

Integer val1 = new Integer(5);
Integer val2 = new Integer(5);

Now, to check whether they are equal or not, let us use the == operator.

(val1 == val2)

Let us now see the complete example.

Example

 Live Demo

public class Demo {
   public static void main( String args[] ) {
      Integer val1 = new Integer(5);
      Integer val2 = new Integer(5);
      Integer val3 = new Integer(10);
      System.out.println("Integer 1 = "+val1);
      System.out.println("Integer 2 = "+val2);
      System.out.println("Integer 3 = "+val3);
      System.out.println("val1 is equal to val2 = "+(val1 == val2));
      System.out.println("val2 is not equal to val3 = "+(val2 != val3));
   }
}

Output

Integer 1 = 5
Integer 2 = 5
Integer 3 = 10
val1 is equal to val2 = false
val2 is not equal to val3 = true
raja
Published on 13-Nov-2018 05:38:14
Advertisements