Checking two integers equal or not in Java is done by various approaches.
- Arithmetic operator
- Comparison Operators
- String functions
- XOR operator
- Complement (~) and bit-wise (&) operator
Example
Input: FirstNumber = 15 SecondNumber= 15 Output: Numbers are same Input: FirstNumber = 15 SecondNumber= 25 Output: Numbers are not same
Approach #1: Arithmetic Operator
If two numbers are equal then their subtraction is equal to 0.
// Check Two Integers are Equal or Not in Java // using arithmetic operator import java.io.*;
class GFG {
public static void main(String[] args)
{
int firstNumber = 15 ;
int secondNumber = 15 ;
if ((firstNumber - secondNumber) == 0 )
System.out.println( "Numbers are equal" );
else
System.out.println( "Numbers are not equal" );
}
} |
Numbers are equal
Approach #2: Comparison Operators
If two numbers are equal then equal operator in if condition returns true, else return false.
// Check Two Integers are Equal or Not in Java // using Comparison Operators import java.io.*;
class GFG {
public static void main(String[] args)
{
int firstNumber = 15 ;
int secondNumber = 15 ;
if (firstNumber == secondNumber)
System.out.println( "Numbers are equal" );
else
System.out.println( "Numbers are not equal" );
}
} |
Numbers are equal
Approach #3: String functions
Convert Numbers to string and use compareTo() method in the string class. compareTo() method returns 0 if both strings are same, else returns 1 or -1.
// Check Two Integers are Equal or Not in Java // using String functions import java.io.*;
class GFG {
public static void main(String[] args)
{
String firstNumber = 15 + "" ;
String secondNumber = 15 + "" ;
if (firstNumber.compareTo(secondNumber) == 0 )
System.out.println( "Numbers are equal" );
else
System.out.println( "Numbers are not equal" );
}
} |
Numbers are equal
Approach #4: XOR Operation
XOR property states that XOR of the two same numbers is zero.
// Check Two Integers are Equal or Not in Java // using XOR Operation import java.io.*;
class GFG {
public static void main(String[] args)
{
int firstNumber = 15 ;
int secondNumber = 15 ;
if ((firstNumber^secondNumber)== 0 )
System.out.println( "Numbers are equal" );
else
System.out.println( "Numbers are not equal" );
}
} |
Numbers are equal
Approach #5: Complement (~) and Bit-wise (&) Operator
// Check Two Integers are Equal or Not in Java import java.io.*;
class GFG {
public static void main(String[] args)
{
int firstNumber = 15 ;
int secondNumber = 15 ;
if ((firstNumber & ~secondNumber) == 0
&& (~firstNumber & secondNumber) == 0 )
System.out.print( "Numbers are equal" );
else
System.out.print( "Numbers are not equal" );
}
} |
Numbers are equal