Java to Find the Largest Number Among Three Numbers

Greatest of three numbers using java :

 

In this article, we will simply create a program i.e. java program to find the greatest of three numbers. We will ask the user to enter three numbers and check which is greater among them.

We will do this by comparing each number with other numbers, one by one, in the form of different conditions with the help of if-else statement.

Greatest of three numbers using java

Working :

Step 1 : Ask the user to enter three numbers.

Step 2 : Use the condition to check which number is greater among three.

  • If the first number is greater than the second number and third number then print that first number is greatest.
  • If the second number is greater than the first number and third number then print that second number is greatest.
  • If the third number is greater than the first number and the second number then print that third number is greatest.
  • Otherwise, all three numbers are equal.

Step 3 : Print the resultant as per above conditions.

Code in Java :

//Java program to find greatest of three numbers
import java.util.Scanner;
public class greatest_of_three_numbers
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input three numbers from user
System.out.print("Enter the first number : ");
int first = sc.nextInt();
System.out.print("Enter the second number : ");
int second = sc.nextInt();
System.out.print("Enter the third number : ");
int third = sc.nextInt();
System.out.println();
//condition for first number
if(first > second && first > third)
System.out.println(first+" is the greatest number.");
//condition for second number
else if(second > first && second > third)
System.out.println(second+" is the greatest number.");
//condition for third number
else if(third > first && third > second)
System.out.println(third+" is the greatest number.");
//condition when all three numbers are equal
else
System.out.println("All three numbers are same");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter the first number : 12

Enter the second number : 43

Enter the third number : 34

43 is the greatest number.



Enter the first number : 12

Enter the second number : 12

Enter the third number : 12

All three numbers are same