C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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


Liked this article? Do share with your friends :)


COMMENTS