Home » Java Basics » if/else statement » Compare integers

About Ilias Tsagklis

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

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);
		}
		
	}

}

Output:

12 is less than 43

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments