Java: max() and min() methods java.lang.Math


Let's take a look at the Math class from java.lang which has the static max and min methods that can be used to find the max and the min of two numbers passed in as a input argument.

Example:
package org.example;

public class MaxMinAvgExample {

    public static void main(String[] args) {

        int no1 = 10;
        int no2 = 20;

        //max
        System.out.println("Max number is: " + Math.max(no1, no2));

        //min
        System.out.println("Min number is: " + Math.min(no1, no2));
        
    }
}

Output:
Max number is: 20
Min number is: 10

More Examples:
Math.max(14, 12)         -> Output: 12 
Math.min(-1, 2)          -> Output: -1

Math.max(14.2, 14.3)        -> Output: 14.3 
Math.min(2.2, 4.5)          -> Output: 2.2
		

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap