zParacha.

Effective Programming Tips

← Home

How to find largest and smallest numbers from input in Java

November 23, 2017

Following simple Java program shows how to read input values and then print smallest and largest values. It reads the input from standard input using Scanner and then uses methods from Math class to determine the largest and smallest numbers entered by the user.

package com.zparacha.utils;

import java.util.NoSuchElementException;
import java.util.Scanner;

public class LargestSmallestValues {

	public static void main(String[] args) {
		try (Scanner in = new Scanner(System.in)) {
			System.out.print("Please enter numbers:(Enter , to stop)");
			double largest = in.nextDouble();
			double smallest = largest;
			while (in.hasNextDouble()) {
				double input = in.nextDouble();
				largest = Math.max(largest, input);
				smallest = Math.min(smallest, input);
			}

			System.out.println("Smallest Value is " + smallest);
			System.out.println("Largest Value is " + largest);

		} catch (NoSuchElementException e) {
			System.out.println("No numbers were entered.");
		}
	}

}

A more modern way to do this (Java 8+)

If you already have the numbers in a collection rather than reading them one at a time from Scanner, DoubleSummaryStatistics gets you the min, max, count, sum, and average in a single pass — and it still reads the same way on JDK 21:

DoubleSummaryStatistics stats = numbers.stream()
    .mapToDouble(Double::doubleValue)
    .summaryStatistics();

System.out.println("Smallest Value is " + stats.getMin());
System.out.println("Largest Value is " + stats.getMax());