Signup/Sign In
LAST UPDATED: SEPTEMBER 18, 2020

Java Long max() Method

Java max() method is a part of the Long class of the java.lang package and is specified by the Math.max() method of the Math class. This method is used to return the numerically greater value(maximum value) of the two numbers passed as arguments.

If a positive and a negative number is passed then the positive value is returned but if both the numbers passed are negative then lower magnitude value is returned.

Syntax:

public static long max(long a, long b)

Parameters:

The parameters passed are the long values by the user to check for the maximum of the two numbers passed.

Returns:

The numerically greater value out of the two values passed as the parameter.

Example 1:

Here, one positive and one negative number is taken, hence the positive value is returned and in the case of both negative, the value with lower magnitude is returned.

import java.lang.Long;

public class StudyTonight 
{  
    public static void main(String[] args) 
    {  
          
          long x = 5485L;  
          long y = -3242L; 
          long z = -5645L;
           
    
          System.out.println("Greater number is " + Long.max(x, y));  // print the larger number between x and y 
          System.out.println("Greater number is " + Long.max(y, z));  // print the larger number between y and z
    }  
}


Greater number is 5485
Greater number is -3242

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner; 

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
           System.out.println("Enter the Two values: ");  
           Scanner sc= new Scanner(System.in);  
           long a = sc.nextLong();  
           long b = sc.nextLong();  
                       
           System.out.println("Larger value is " + Long.max(a, b)); //Print the larger number between a and b 
          
        }
        catch(Exception e)
        {
          
        }
         
    }  
}  


Enter the Two values:
-674 -754
Larger value is -674
***************************
Enter the Two values:
890 -423
Larger value is 890

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.