Skip to main content

Practical-3

Write a Java Program that will find the largest no from the given two nos.

  1. Introduction: In Java programming language, one can use an if-else control statement to identify and compare two numbers. If the numbers are equal, it prints 'Both numbers are equal' or else it prints the greater of the two numbers. This program can also be used to compare two string values. To build this program, a comparison operator is used to check if the two numbers are equal or not. By using this operator, one can also find the largest number out of two given numbers.

Code

import java.util.Scanner;

class LargestOfTwo {

public static void main(String args[]) {
int x, y;
Scanner sc = new Scanner(System.in);

System.out.println("Enter two integers:");
x = sc.nextInt();
y = sc.nextInt();

if (x > y)
System.out.println(x + " is greater than " + y);

else if (x < y)
System.out.println(y + " is greater than " + x);

else
System.out.println("Both numbers are equal");
}
}

Output

If the user inputs two numbers say 10 and 20, then the output will be:

20 is greater than 10


Explanation

The program first defines two integer variables to store the two numbers. These two numbers are then taken from the user as input and stored in these two variables. An if-else statement is then used to compare these two numbers and identify the largest one out of the two. If x is greater than y, then x is printed as the larger number or else y is printed as the larger number. If the two numbers turn out to be the same, then a message saying 'Both numbers are equal' will be printed.