# How to compare two integers in java

In this blog, we would discuss How to compare two integers in java. When comparing two integers in Java, there are a few different ways to do it. The most common way is to use the **==** operator, which will return true if the two values are equal, and false if they are not. Another way to compare two integers is to use the** !=** operator, which will return true if the two values are not equal, and false if they are.

Finally, you can also use the **> or <** operators to compare two integers. These will return true if the first value is greater than (or less than) the second value, and false if it is not. So, which method should you use when comparing two integers in Java? It really depends on what you’re trying to do. If you just need to know if the two values are equal, then using the **==** operator is probably the easiest way to do it. But if you need to know if the two values are not equal, or if one value is greater than the other, then using the **!=, >, or <** operators might be a better choice.

## What is compareTo() method

If you want to compare two integers that may be different types, you can use the **compareTo()** method. This method returns an integer that is less than, equal to, or greater than zero, depending on whether the first integer is less than, equal to, or greater than the second integer.

You can also use the **compareTo()** method to sort a list of integers. The **compareTo()** method is used by the **Collections.sort()** method to sort a list of objects. Finally, you can use the **Integer.compare()** method to compare two integers. This method is similar to the **compareTo()** method, but it takes two integer values as arguments, rather than an integer and an object.

## Implementation of Comparision of two integers in java

Here is an example of how to compare two integers in Java:

class HelloWorld { public static void main(String[] args) { int a = 5; int b = 10; if (a == b) { System.out.println("a is equal to b"); } else if (a < b) { System.out.println("a is less than b"); } else if (a > b) { System.out.println("a is greater than b"); } } }

**Output**

You can also use the** compareTo()** method to compare two integers:

class Abhi { public static void main(String[] args) { int a = 5; int b = 10; int result = a.compareTo(b); if (result < 0) { System.out.println("a is less than b"); } else if (result == 0) { System.out.println("a is equal to b"); } else if (result > 0) { System.out.println("a is greater than b"); } } }

**Output**

And here is the same example using the** Math.max()** and** Math.min()** methods:

class HelloWorld { public static void main(String[] args) { int a = 5; int b = 10; if (Math.max(a, b) == a) { System.out.println("a is greater than b"); } else if (Math.min(a, b) == a) { System.out.println("a is less than b"); } else { System.out.println("a is equal to b"); } } }

**Output**

Also, read about **Regex** and its implementation.