How do I get the minimum or maximum value between two numbers?

The code below show you how to use the Math.min() and Math.max() method call the get the minimum and maximum value between two numbers. As other method in the Math class these methods also overloaded to accept many types of primitive data.

package org.kodejava.example.math;

public class GetMaxMinValueExample {
    public static void main(String[] args) {

        Double value1 = 100.0D;
        Double value2 = 200.0D;

        double max1 = Math.max(value1, value2);
        double min1 = Math.min(value1, value2);

        float max2 = Math.max(value1.floatValue(), value2.floatValue());
        float min2 = Math.min(value1.floatValue(), value2.floatValue());

        int max3 = Math.max(value1.intValue(), value2.intValue());
        int min3 = Math.min(value1.intValue(), value2.intValue());

        long max4 = Math.max(value1.longValue(), value2.longValue());
        long min4 = Math.min(value1.longValue(), value2.longValue());

        System.out.println("Max value in double: " + max1);
        System.out.println("Min value in double: " + min1);
        System.out.println("Max value in float : " + max2);
        System.out.println("Min value in float : " + min2);
        System.out.println("Max value in int   : " + max3);
        System.out.println("Min value in int   : " + min3);
        System.out.println("Max value in long  : " + max4);
        System.out.println("Min value in long  : " + min4);

The result of the above program are:

Max value in double: 200.0
Min value in double: 100.0
Max value in float : 200.0
Min value in float : 100.0
Max value in int   : 200
Min value in int   : 100
Max value in long  : 200
Min value in long  : 100
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply