if-else
statement to determine which number is larger.
public class LargestOfTwoNumbers
{
public static void main(String[] args)
{
int no1=10, no2=20;
// Finding and displaying the largest number
if (no1 > no2)
{
System.out.println("The largest number is : " + no1);
}
else if (no2 > no1)
{
System.out.println("The largest number is : " + no2);
}
else
{
System.out.println("Both numbers are equal.");
}
}
}
The largest number is : 20
import java.util.Scanner;
public class LargestOfTwoNumbers
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
int no1 = scanner.nextInt();
System.out.print("Enter number 2: ");
int no2 = scanner.nextInt();
// Finding and displaying the largest number
if (no1 > no2)
{
System.out.println("\nThe largest number is : " + no1);
}
else if (no2 > no1)
{
System.out.println("\nThe largest number is : " + no2);
}
else
{
System.out.println("\nBoth numbers are equal.");
}
scanner.close();
}
}
Enter number 1: 100 Enter number 2: 200 The largest number is : 200
Scanner
class is imported to take user input.
no1
and no2
) are declared to store the user’s input.
scanner.nextInt()
to read integer values from the user.
if
condition checks if no1
is greater than no2
and prints it as the largest.
else if
condition is true, no2
is the largest.
scanner.close()
method is used to close the input stream and release resources.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.