Java Program to Find Smallest of Two Numbers

In this tutorial, you will learn how to write a Java program to find the smallest of two numbers. We will first understand the comparison logic and then implement it using different approaches in Java.

Finding the smaller value between two numbers is a basic Java programming problem that is useful for beginners to understand important concepts such as:

  • Relational operators
  • if-else statements
  • Taking input using the Scanner class
  • Ternary operator
  • Comparing integer and decimal numbers
  • Handling equal numbers

We will cover the following approaches in this tutorial:

  • Find the smallest of two numbers using if-else.
  • Find the smallest of two numbers using Scanner.
  • Find the smallest of two numbers using the ternary operator.
  • Find the smallest of two decimal numbers.
  • Find the smallest of two numbers using Math.min().

How to Find the Smallest of Two Numbers in Java?

To find the smallest of two numbers, we compare the two values. Suppose we have two numbers, num1 and num2. The basic comparison logic between these two numbers is:

  • If num1 < num2, then num1 is the smallest number.
  • If num2 < num1, then num2 is the smallest number.
  • If neither number is smaller, both numbers are equal.

Java provides relational operators such as <, >, <=, and >= to compare numerical values. For finding the smallest of two numbers, the less-than (<) operator is commonly used.

Java Program to Find Smallest of Two Numbers Using If-Else

The simplest way to find the smallest of two numbers is by using an if-else if-else statement. In this approach, we will directly assign values to variables. Here is an example to find the smallest numbers in Java.

Example 1: Using Hardcoded Numbers

/**
 * A Java program to find the smallest of two numbers 
 * using standard if-else conditional statements.
 */
public class SmallestOfTwoNumbers {
    
    /**
     * Main method - the entry point of the Java application.
     * @param args Command-line arguments (not used in this program)
     */
    public static void main(String[] args) {

        // Step 1: Declare and initialize the two numbers we want to compare
        int num1 = 45;
        int num2 = 72;

        // Step 2: Compare the values using relational operators (<, ==)
        if (num1 < num2) {
            // This block executes if num1 is strictly smaller than num2
            System.out.println(num1 + " is the smallest number.");
            
        } else if (num2 < num1) {
            // This block executes if num2 is strictly smaller than num1
            System.out.println(num2 + " is the smallest number.");
            
        } else {
            // This block executes if neither is smaller, meaning they have the same value
            System.out.println("Both numbers are equal.");
        }
    }
}

Expected Output:

45 is the smallest number.

In this example program:

  • We declare two integer variables, num1 and num2, and assign 45 to num1 and 72 to num2.
  • The condition num1 < num2 checks whether 45 is smaller than 72. Since the condition is true, the program prints 45 as the smallest number.
  • If the first condition is false, the program checks whether num2 is smaller than num1.
  • If both conditions are false, the two numbers must be equal.

Therefore, the program correctly identifies the smaller value.

Java Program to Find Smallest of Two Numbers Using Scanner

In the previous example, we have directly assigned values to variables. However, in real applications, we often need to accept values from the user. Therefore, Java provides the Scanner class to read input from the keyboard.

Example 2: Taking User Input

import java.util.Scanner;
/**
 * A Java program to find the smallest of two numbers 
 * by taking dynamic input from the user using the Scanner class.
 */
public class SmallestUsingScanner {
    
    /**
     * Main method - the entry point of the Java application.
     * @param args Command-line arguments
     */
    public static void main(String[] args) {

        // Step 1: Create a Scanner object to read input from the console
        Scanner scanner = new Scanner(System.in);

        // Step 2: Prompt the user to enter the first number and store it
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        // Step 3: Prompt the user to enter the second number and store it
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Step 4: Compare the two numbers using relational operators
        if (num1 < num2) {
            // Executes if num1 is strictly less than num2
            System.out.println("The smallest number is: " + num1);
        } else if (num2 < num1) {
            // Executes if num2 is strictly less than num1
            System.out.println("The smallest number is: " + num2);
        } else {
            // Executes if neither condition is met, meaning they are equal
            System.out.println("Both numbers are equal.");
        }

        // Step 5: Close the scanner to prevent memory leaks and resource leaks
        scanner.close();
    }
}

Expected Output:

Enter the first number: 85 
Enter the second number: 42 
The smallest number is: 42

In this example program:

  • The statement import java.util.Scanner; imports the Scanner class from the java.util package.
  • We then create a Scanner object: Scanner scanner = new Scanner(System.in);
  • The nextInt() method reads integer values entered by the user:
    • int num1 = scanner.nextInt();
    • int num2 = scanner.nextInt();
  • The program then compares the two numbers using if-else statements and displays the smaller value.
  • Finally, we close the Scanner object using scanner.close();.

Java Program to Find Smallest of Two Numbers Using Ternary Operator

The ternary operator (?:) in Java provides a shorter way to perform a simple conditional operation. The general syntax to use the ternary operator is:

condition ? valueIfTrue : valueIfFalse;

To find the smallest of two numbers, we can write:

int smallest = (num1 < num2) ? num1 : num2;

If num1 < num2 is true, num1 is assigned to the smallest variable. Otherwise, num2 is assigned.

Example 3: Using Ternary Operator

/**
 * A Java program to find the smallest of two numbers 
 * using the ternary operator (?:).
 */
public class SmallestUsingTernary {
    public static void main(String[] args) {

        // Declare and initialize two numbers
        int num1 = 45;
        int num2 = 72;

        // Use the ternary operator to find the smaller value
        int smallest = (num1 < num2) ? num1 : num2;

        // Output the result
        System.out.println("The smallest number is: " + smallest);
    }
}

Expected Output:

The smallest number is: 45

How Does the Ternary Operator Work?

Consider this statement:

int smallest = (num1 < num2) ? num1 : num2;

It works as follows:

  • If the condition num1 < num2 is true, num1 is selected.
  • If the condition is false, num2 is selected.
  • The selected value is stored in the smallest variable.

Handling Equal Numbers

Suppose both numbers are 40:

int num1 = 40;
int num2 = 40;

int smallest = (num1 < num2) ? num1 : num2;

The condition num1 < num2 is false because both values are equal. Therefore, num2 is selected. The numerical result is still correct because both numbers have the same value.

If you want to explicitly display an equality message, you can use:

String result = (num1 == num2) ? "Both numbers are equal." :
                (num1 < num2) ? num1 + " is the smallest." :
                 num2 + " is the smallest.";
System.out.println(result);

Java Program to Find Smallest of Two Decimal Numbers

The same comparison logic can also be used with decimal numbers. For decimal values, Java commonly uses the double data type.

Example 4: Comparing Two Decimal Numbers

/**
 * A Java program to find the smallest of two decimal (double) numbers 
 * using standard if-else conditional statements and relational operators.
 */
public class SmallestOfTwoDecimals {
    /**
     * Main method - the entry point of the Java application.
     * @param args Command-line arguments (not used in this program)
     */
    public static void main(String[] args) {

        // Step 1: Declare and initialize two decimal numbers using the double data type
        double num1 = 45.75;
        double num2 = 52.33;

        // Step 2: Compare the two decimal values using relational operators (<)
        if (num1 < num2) {
            // This block executes if num1 is strictly smaller than num2
            System.out.println(num1 + " is the smallest number.");
            
        } else if (num2 < num1) {
            // This block executes if num2 is strictly smaller than num1
            System.out.println(num2 + " is the smallest number.");
            
        } else {
            // This block executes if neither is smaller, meaning they have the exact same value
            System.out.println("Both decimal numbers are equal.");
        }
    }
}

Expected Output:

45.75 is the smallest number.

The less than (<) operator works with double values in the same way that it works with integer values.

Java Program to Find the Smallest of Two Numbers Using Math.min()

Java also provides the built-in Math.min() method for finding the smaller of two numeric values. The basic syntax to use the min() method is:

Math.min(value1, value2);

This method returns the smaller of the two supplied values.

Example 5: Using Math.min()

/**
 * A Java program to find the smallest of two numbers 
 * using Java's built-in Math.min() utility method.
 */
public class SmallestUsingMathMin {
    /**
     * Main method - the entry point of the Java application.
     * @param args Command-line arguments
     */
    public static void main(String[] args) {

        // Step 1: Declare and initialize two integer numbers to compare
        int num1 = 45;
        int num2 = 72;

        // Step 2: Use Math.min() to automatically find and return the smaller of the two values
        int smallest = Math.min(num1, num2);

        // Step 3: Print the result to the console
        System.out.println("The smallest number is: " + smallest);
    }
}

Expected Output:

The smallest number is: 45

This approach is concise and useful when you simply need the smaller value without writing an explicit conditional statement. You can also use the Math.min() method with decimal values.

If you are beginners, you should first learn with the if-else approach because it clearly demonstrates how comparison and decision-making work. Once you understand the basic logic, you can learn the ternary operator and Math.min() for shorter solutions.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.