Open In App

Java Math max() Method

Last Updated : 14 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The max() method in Java is a part of java.lang.Math class. This is an inbuilt function in Java that returns maximum of two numbers. This method can work with any type of number, such as int, float, long, and double.

Special Cases:

  • If a negative and a positive number are passed as arguments, then the positive result is generated.
  • If both parameters passed are negative, then the number with the lower magnitude is generated as a result.

Syntax of max() Method

dataType max(dataType num1, dataType num2)

Note: Here, data type can be int, float, long, or double.

  • Parameter: This method accepts two parameters num1 and num2 among which the maximum is returned.
  • Return Type: The function returns maximum of two numbers. The datatype will be the same as that of the arguments.

Let's now discuss some examples for better understanding.


Examples of Java Math max() Method

Example 1: In this example, we will see the basic usage of Math.max() method with Double values.

Java
// Java program to demonstrate 
// the use of max() function
// when two double data-type 
// numbers are passed as arguments
import java.lang.Math;

public class Geeks {
    
    public static void main(String args[]) {
        
        double a = 12.123;
        double b = 12.456;

        // prints the maximum of two numbers
        System.out.println(Math.max(a, b));  
    }
}

Output
12.456


Example 2: In this example, we will see the usage of Math.max() method with integer values including both positive and negative number.

Java
// Java program to demonstrate 
// the use of max() function
// when one positive and one 
// negative integer are passed 
// as argument
import java.lang.Math;

public class Geeks {
    
    public static void main(String args[]) {
        
        int a = 23;
        int b = -23;

        // prints the maximum of two numbers
        System.out.println(Math.max(a, b));  
    }
}

Output
23


Example 3: In this example, we will see the usage of Math.max() method with two negative numbers.

Java
// Java program to demonstrate the 
// use of max() function when two 
// negative integers are passed as arguments
import java.lang.Math;

public class Geeks {
    
    public static void main(String args[]) {
        
        int a = -25;
        int b = -23;

        // prints the maximum of two numbers
        System.out.println(Math.max(a, b)); 
    }
}

Output
-23

Practice Tags :

Similar Reads