Java Greatest of Three Numbers Program

Java Greatest of Three Numbers Program reads three numbers from the user and returns the greatest among them. The program is created by using Nested-If Statement for comparing the three numbers.

The logic of the program is as discussed –

  • In first if condition number 1 is compared with number 2 and number 2 is compared with number 3. If both these conditions are true then number1 will be printed as the greatest.
  • In the else part of first If statement, number2 is compared with number 1 and number 3. If both these conditions become true then number2 is printed as the greatest among three numbers.
  • If the both If statements prior to this else are false then number 3 is printed as the greatest.

Java Greatest of Three Numbers Code

Let’s see how the above logic is implemented as program in Java Greatest of Three Numbers.

//Program to read three numbers and find and print the largest Number
import java.util.*;
public class GreatestOfThree
{ 
	public static void main(String[] args) 
	{ 
		//Create a scanner object
		Scanner scObj = new Scanner (System.in);
		// Declare three number variables
		int intNum1, intNum2, intNum3; 
		//Read three numberd frp=om user
		System.out.println("Enter First Number"); 
		intNum1=scObj.nextInt();
		System.out.println("Enter Second Number"); 
		intNum2=scObj.nextInt();
		System.out.println("Enter Third Number"); 
		intNum3=scObj.nextInt();
		//Check first number for greatest 
		if(intNum1>=intNum2 && intNum2>=intNum3) 
		System.out.println(intNum1+" is the Greatest Number"); 
		//Check second number for greatest 
		else if (intNum2>=intNum1 && intNum2>=intNum3) 
		System.out.println(intNum2+" is the Greatest Number"); 
		else 
		//else third number is greatest 
		System.out.println(intNum3+" is the Greatest Number"); 
	} 
}

Output

output -Java Greatest of Three Numbers Program

Read here to understand the structure of a Java program. To download Latest version of java click here