Comparing Integers in Java | Java Practice Question – 3

Write a Java Program that asks the user to enter two integers, obtains them from the user and displays the larger number followed by the word "is larger". if the numbers are equal, print the message "These numbers are equal".

Firstly, We have to import Java’s predefined Scanner Class from package java.util

import java.util.Scanner

Now, Begins the declaration of class Comparing Integers. and remember, the file name for this public class must be Comparing

public class ComparingIntegers

Note – Don’t forget an opening and closing braces.

Create the main method of java. that is available on every java program

public static void main(String [] args)

Note – Don’t forget an opening and closing braces.

Declaring and Creating a Scanner to Obtain User Input from the Keyboard.

Scanner input = new Scanner;

Declaring Variables to Store int

int number1;
int number2;

Prompting the User for input and Obtaining int as input from the user

System.out.print("Enter Value of First Number - ");
number1 = input.nextInt();

System.out.print("Enter Value of Second Number - ");
number2 = input.nextInt();

It’s time to compare both integers using if-else statement and Display

if (number1 > number2)
    system.out.printf("%d is larger", number1);
else if (number2 > number1)
    system.out.printf("%d is Larger", number2);
    system.out.print("These numbers are equal");

Source Code

import java.util.Scanner;
public class ComparingIntegers
  public static void main(String[] args)
    Scanner input = new Scanner(;
    int number1, number2;
    System.out.print("Enter the Value of Number1 -");
    number1 =- input.nextInt();
    System.out.print("Enter the Value of Number2 -");
    number2 = input.nextInt();
    if (number1 > number2)
      System.out.printf("%d is larger",number1);
    else if (number2 > number1)
      System.out.printf("%d is larger",number2);
      System.out.print("These numbers are equal");

Leave a Reply

Your email address will not be published. Required fields are marked *