if/else statement
Compare integers
With this example we are going to demonstrate how to compare integers. The comparation between two integers can be performed using the greater than
and less than
symbols. In short, to compare two integers i1
and i2
you should:
- Check if
i1
is greater thani2
in anif
statement. If it is true, that means thati1
is greater thani2
. - Check if
i1
is less thani2
in anelse if
statement. If it is true, that means thati1
is less thani2
. - Code inside the
else
statement will be executed when aboveif
statements are both false.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.basics; public class CompareIntegers { public static void main(String[] args) { int i1 = 12; int i2 = 43; if (i1 > i2) { System.out.println(i1 + " is greater than " + i2); } else if (i1 < i2) { System.out.println(i1 + " is less than " + i2); } else { System.out.println(i1 + " is equal to " + i2); } } }
Output:
12 is less than 43
This was an example of how to compare integers in Java.