Find Greatest among three numbers in Java

In this tutorial you will learn how to write a program in C to find largest of three numbers. Determining the greatest among three numbers is a common task that often arises in various applications and algorithms. Whether you’re working on a simple console application or a complex software system, finding maximum value among three given numbers is a fundamental requirement.

In this post, we will explore different approaches to find the greatest among three numbers in Java. We will cover traditional if-else statements, Java 8 concepts and also will use ternary operator for a more concise solution.

Read This: C program to find greatest among three.

How this java program will behave?

Suppose if someone give 3 numbers as input 12, 15 and 10 then our program should return 15 as a output because 15 is a greatest among three.

Example

Enter the first number:
10
Enter the second number:
45
Enter the third number:
28

In this example, the user has entered three numbers: 10, 45, and 28. The program will then determine the greatest among these numbers using the if-else statements.

The output will be:

The greatest number is: 45

Here’s how the program evaluates the numbers:

  • Is 10 greater than or equal to 45 and 28? No.
  • Is 45 greater than or equal to 10 and 28? Yes.
  • Therefore, the greatest number among 10, 45, and 28 is 45.

Program 1: Java program to Find greatest of three numbers

import java.util.*;  
class Main{
    public static void main(String ...args){
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter first number a = ");  
        int a= sc.nextInt();  
        System.out.print("Enter second number b = ");  
        int b= sc.nextInt();  
        System.out.print("Enter third number c = ");  
        int c= sc.nextInt();  
        if(a>=b && a>=c)
    		System.out.println(String.format("Greatest number is a = %d",a));
    	if(b>=a && b>=c)
    		System.out.println(String.format("Greatest number is b = %d",b));
    	if(c>=a && c>=b)
    		System.out.println(String.format("Greatest number is c = %d",c));
    }
} 

Output:

Enter first number a = 45
Enter second number b = 23
Enter third number c = 54
Greatest number is c = 54

Program Explanations

  1. Imports and Class Definition:
    • The program imports the java.util.* package, which includes the Scanner class used for reading user inputs.
    • It defines a class named Main.
  2. Main Method:
    • The main method is declared with varargs (...args), which allows it to accept an array of strings as arguments, though these aren’t used in this program.
  3. Input Collection:
    • A Scanner object named sc is created to read inputs from the standard input stream (keyboard).
    • The user is prompted to enter three integers, a, b, and c, one by one. These values are read and stored in corresponding variables.
  4. Determination of the Greatest Number:
    • The program uses three separate if statements to determine which of the three numbers is the greatest:
      • The first if statement checks if a is greater than or equal to both b and c. If true, it prints a as the greatest.
      • The second if statement checks if b is greater than or equal to both a and c. If true, it prints b as the greatest.
      • The third if statement checks if c is greater than or equal to both a and b. If true, it prints c as the greatest.
  5. Output:
    • Depending on which condition is met, the program prints out the greatest number using System.out.println. The output is formatted to indicate which of the three values (a, b, or c) is the greatest.

Program 2: Find Maximum among three using Java 8

import java.util.*;
public class GreatestAmongThree {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 45;
        int num3 = 28;
        int greatestNumber = Arrays.stream(new int[] {num1, num2, num3})
                .max().orElseThrow(()->new NoSuchElementException("array should not be empty"));
        System.out.println("The greatest number is: " + greatestNumber);
    }
}

Output:

The greatest number is: 45

Program Explanations

  1. Class Declaration:
    • Defines a public class named GreatestAmongThree.
  2. Main Method:
    • The main method serves as the entry point for the program.
  3. Variable Initialization:
    • Three integer variables, num1, num2, and num3, are initialized with values 10, 45, and 28, respectively.
  4. Finding the Greatest Number:
    • The program uses the Arrays.stream() method to create a stream from an array containing num1, num2, and num3.
    • It then applies the .max() method on this stream, which returns an OptionalInt representing the maximum value found in the stream.
    • The orElseThrow() method is called on the result to either get the maximum value or throw a NoSuchElementException if the array is empty (though in this context, the array will never be empty).
  5. Output:
    • Prints the greatest number among the three using System.out.println, showcasing the value stored in greatestNumber.

Program 3: Find Maximum among three using Java 8 and function

import java.util.Arrays;

public class GreatestAmongThree {
    public static void main(String[] args) {
        int num1 = 20;
        int num2 = 45;
        int num3 = 58;

        int greatestNumber = findGreatestNumber(num1, num2, num3);

        System.out.println("The greatest number is: " + greatestNumber);
    }

    private static int findGreatestNumber(int... numbers) {
        return Arrays.stream(numbers)
                .max()
                .orElseThrow(() -> new IllegalArgumentException("At least one number is required"));
    }
}

Output:

The greatest number is: 58

Program Explanations

  1. Class Definition:
    • The class GreatestAmongThree is defined as a public class, allowing it to be accessible from other classes.
  2. Main Method:
    • Variable Initialization: Three integer variables num1, num2, and num3 are initialized with the values 20, 45, and 58, respectively.
    • Method Call: The main method calls findGreatestNumber(num1, num2, num3), passing the three numbers as arguments.
    • Output: It then prints the result returned by findGreatestNumber, stating which number is the greatest.
  3. findGreatestNumber Method:
    • Parameter: The method findGreatestNumber is defined with a varargs parameter int... numbers, which allows it to accept any number of integer arguments.
    • Stream Processing:
      • The numbers are converted into a stream using Arrays.stream(numbers).
      • The stream’s .max() method is used to find the maximum number in the stream. This method returns an OptionalInt, which is a container object that may or may not contain an int value (it depends if the stream is empty or not).
      • The orElseThrow() method on OptionalInt is invoked to either return the maximum value found or throw an IllegalArgumentException if no numbers were passed to the method (though in this context, this exception will never be thrown because the method is always called with three integers).

Conclusion

In this tutorial we have explored different approaches to write a java program to find the greatest among three numbers. The task of determining the maximum value among three given numbers is fundamental and used in various applications and algorithms. The tutorial covered traditional if-else statements, Java 8 concepts using streams, and using functions.

The tutorial provided a comprehensive example with user input, and also default inputs. And in output our program is correctly displaying the greatest number among the given input.

Three programs were presented, each showing a different approach:

  1. Program 1: Traditional if-else Statements
    • This program used if-else statements to compare elements and find the greatest among three numbers.
  2. Program 2: Java 8 Stream API
    • This program using Java 8 features, like Stream API and the max() function to find the maximum among three numbers.
  3. Program 3: Java 8 with a Separate Function
    • This program is also using Java 8 approach, but here we have created a separate function that will return maximum among three.

I hope this tutorial helped you in understanding to find the maximum among three in java.

Happy Coding !!

Leave a Comment