Thursday, January 30, 2025
HomeProgrammingJava Math min() method with Examples

Java Math min() method with Examples

The Math.min() method in Java is used to return the smaller of two values. It is a static method, meaning you can call it without creating an instance of the Math class. The method has two overloaded versions:

  1. Math.min(int a, int b): Returns the smaller of two int values.
  2. Math.min(double a, double b): Returns the smaller of two double values.

Syntax:

Math.min(a, b);

Where a and b are the two values to compare.

Example 1: Using Math.min(int a, int b):

public class MinExample {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        
        // Find the minimum of two numbers
        int result = Math.min(num1, num2);
        System.out.println("The minimum value is: " + result);
    }
}

Output:

The minimum value is: 10

Example 2: Using Math.min(double a, double b):

public class MinExample {
    public static void main(String[] args) {
        double num1 = 15.75;
        double num2 = 20.50;
        
        // Find the minimum of two doubles
        double result = Math.min(num1, num2);
        System.out.println("The minimum value is: " + result);
    }
}

Output:

The minimum value is: 15.75

Example 3: Using Math.min() in a more complex expression:

public class MinExample {
    public static void main(String[] args) {
        int a = 5;
        int b = 8;
        int c = 3;
        
        // Find the smallest among three numbers using nested Math.min()
        int minValue = Math.min(Math.min(a, b), c);
        System.out.println("The minimum value is: " + minValue);
    }
}

Output:

The minimum value is: 3

Example 4: Comparing negative and positive values:

public class MinExample {
    public static void main(String[] args) {
        int num1 = -5;
        int num2 = 3;
        
        // Compare a negative and a positive number
        int result = Math.min(num1, num2);
        System.out.println("The minimum value is: " + result);
    }
}

Output:

The minimum value is: -5

The Math.min() method is useful when you need to find the minimum of two values and is commonly used in various scenarios like validating inputs, calculating bounds, or working with ranges.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x