Home » Java programs » Java basic programs

Java program to compare two numbers with each other



Here, we are implementing a java program that will read two integer number and compare them each other. Program will print which is smallest, largest and equal (if they are) number.
Submitted by IncludeHelp, on December 10, 2017

Given two integer numbers and we have to compare them with each other using java program.

Example:

    Input:
    Enter first number : 12
    Enter second number : 10

    Output:
    12 != 20
    12 < 20
    12 <= 20

Program to compare two numbers with each other in java

import java.util.Scanner;

public class CompareTwoNumbers
{
	public static void main( String args[] )    
    {
        // create objects       
        Scanner sc = new Scanner(System.in);
        int number1;        
        int number2;   
      
        // enter both the numbers for comparison.
        System.out.print("Enter first number : " );        
        number1 = sc.nextInt();    
 
        System.out.print("Enter second number : " );         
        number2 = sc.nextInt();               
        
        if ( number1 == number2 )           
            System.out.printf( "%d == %d\n", number1, number2 );  
        if ( number1 != number2 )          
            System.out.printf( "%d != %d\n", number1, number2 );  
        if ( number1 < number2 )          
            System.out.printf( "%d < %d\n", number1, number2 );  
        if ( number1 > number2 )          
            System.out.printf( "%d > %d\n", number1, number2 );  
        if ( number1 <= number2 )          
            System.out.printf( "%d <= %d\n", number1, number2 );  
        if ( number1 >= number2 )          
            System.out.printf( "%d >= %d\n", number1, number2 );  
    }
}

Output

First run:
Enter first number : 12
Enter second number : 10
12 != 10
12 > 10
12 >= 10

Second run:
Enter first number : 12
Enter second number : 10
12 != 20
12 < 20
12 <= 20





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.