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 than i2 in an if statement. If it is true, that means that i1 is greater than i2.
  • Check if i1 is less than i2 in an else if statement. If it is true, that means that i1 is less than i2.
  • Code inside the else statement will be executed when above if 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);



12 is less than 43

This was an example of how to compare integers in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button