Comparing Integers in Java using If Statements - Source Code

In this tutorial, I will show you how to compare integers using if statements, relational operators and equality operators.


Source Code


//copyrighted by geekdecoders.blogspot.com
//Compare integers using if statements, relational operators and equality operators
import javax.swing.JOptionPane;

public class Comparison
{
 public static void main( String args [] )
 {
  try
  {
   String snum1=JOptionPane.showInputDialog("Enter Number 1");
   int number1=Integer.parseInt(snum1);

   String snum2=JOptionPane.showInputDialog("Enter Number 2");
   int number2=Integer.parseInt(snum2);
   
   System.out.println("\nResults\n");
  
   if ( number1 == number2)
    System.out.println( number1 + " equal " + number2 );

   if ( number1 != number2)
    System.out.println( number1 + " not equal " + number2 );

   if ( number1 < number2)
    System.out.println( number1 + " less than " + number2 );

   if ( number1 > number2)
    System.out.println( number1 + " greater than " + number2 );

   if ( number1 <= number2)
    System.out.println( number1 + " less than or equal " + number2 );

   if ( number1 >= number2)
    System.out.println( number1 + " greater than or equal " + number2 );   
  }
  catch(NumberFormatException e)
  {
            JOptionPane one = new JOptionPane();
            JOptionPane.showMessageDialog(one,"Enter Valid Integer Value");
  }
 }
}

Results


Comments