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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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