Find Smallest Among Three in Java Program

In this tutorial we will learn writing java program to find the smallest number among the three given numbers. This program will be very simple. Here we are just comparing the numbers using if else statements. And after comparing we will just print the smallest number.

How program will behave?

Our program will take 3 numbers as an input. Now using if else statements we will compare the numbers. Logic of comparison will be like a<=b && a<=c. Here a is smaller because it is smaller than b and c both. For the input 3, 4 and 5, output will be 3.

Program 1: Java Program to Calculate Smallest Among Three

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        int a, b, c;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give the first number");
        a= sc.nextInt();
        System.out.println("Please give the second number");
        b= sc.nextInt();
        System.out.println("Please give the third number");
        c= sc.nextInt();
        if(a<=b && a<=c)
            System.out.println("a is smallest");
        if(b<=a && b<=c)
            System.out.println("b is smallest");
        if(c<=a && c<=b)
            System.out.println("c is smallest");
    }
}

Output

Please give the first number
45
Please give the second number
33
Please give the third number
12
c is smallest

Explanation

The user inputs the integers 6, 2, 7. For these inputs, our program is comparing all three integer inputs with each other to find which one is the smallest. Let’s have a look at the conditions of conditional statements in this

output: 6<=2 and 6<=9, returns ‘False’, 2<=6 and 2<=9, returns ‘True’ , 9<=6 and 9<2, returns ‘False’

So the output is ‘b’ because b value 2 is smallest.

Program 2: Find minimum among three using Java 8

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        int num1, num2, num3;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give the first number");
        num1 = sc.nextInt();
        System.out.println("Please give the second number");
        num2 = sc.nextInt();
        System.out.println("Please give the third number");
        num3 = sc.nextInt();
        int min = Arrays.asList(num1, num2, num3)
                .stream()
                .min(Integer::compare)
                .orElse(0);
        System.out.println("minimum number is ="+ min);
    }
}

Output

Please give the first number
34
Please give the second number
54
Please give the third number
12
minimum number is =12

Hope above program helped you to understand how you can write java program to ding the smallest number among three.