Write a Java method to find the smallest number among three numbers


This Java program prompts the user to enter three numbers and then uses the Math.min method to find and output the smallest number among them. Here's a breakdown of how the program works:

  • The import java.util.Scanner statement is used to import the Scanner class from the java.util package, which allows the program to read input from the user.
  • The public class Smallest_Number statement declares a new class called Smallest_Number, which contains the main method that will be executed when the program runs.
  • The main method begins with the creation of a new Scanner object called input, which is used to read input from the user.
  • The program prompts the user to enter the first number by printing the message "Enter the Number 1 : " to the console, and then reads the input using the nextDouble method of the Scanner object. The input is stored in a variable called n1.
  • Steps 4 and 5 are repeated for the second and third numbers, with the messages "Enter the Number 2 :" and "Enter the Number 3 :", respectively.
  • Finally, the program uses the Math.min method to find the smallest value among the three numbers and prints it to the console along with the message "The smallest value is " using string concatenation.

Source Code

import java.util.Scanner;
public class Smallest_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Number 1 : ");
		double n1 = input.nextDouble();
		System.out.print("Enter the Number 2 : ");
		double n2 = input.nextDouble();
		System.out.print("Enter the Number 3 : ");
		double n3 = input.nextDouble();
		System.out.print("The smallest value is " + Math.min(Math.min(n1, n2), n3));
	}	
}

Output

Enter the Number 1 : 56
Enter the Number 2 : 89
Enter the Number 3 : 34
The smallest value is 34.0

Example Programs