Description

On this document we will be showing a java example on how to use the max() method of Math Class. The max() returns which of the two method argument has the highest value numerically. This method is overloaded such that it handles all primitive data type. Here are the overloaded methods:

  • public static int max(int a, int b)
  • public static long max(long a, long b)
  • public static float max(float a, float b)
  • public static double max(double a, double b)

The overloaded methods are basically the same, it’s just that they deal with different data type either int, long, float, and double

Most of the methods of the Math class is static and the max() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.max(a).

Method Returns

The max() method returns which of the two values (a and b) have the highest numerical value.

Compatibility

Requires Java 1.0 and up

Java Math max() Example

Below is a java code demonstrates the use of max() method of Math class. The example presented might be simple however it shows the behavior of the max() method.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * max() method of Math class
 */

public class MathMaxExample {

	public static void main(String[] args) {
		
		// Ask for user input
		System.out.print("Enter first value:");
		
		// use scanner to read the console input
		Scanner scan = new Scanner(System.in);
		
		// Assign the 1st input to String variable
		String value1 = scan.nextLine();
		
		// ask for the second input
		System.out.print("Enter second value:");
		
		// Assign the 2nd input to String variable
		String value2 = scan.nextLine();
		
		// close the scanner object
		scan.close();		
		
		// convert the values to int
		int a = Integer.parseInt(value1);
		int b = Integer.parseInt(value2);		
			
		// get the result of max method
		int result = Math.max(a,b);
		System.out.print("Result of the operation:"+result);
	}

}

The above java example source code demonstrates the use of max() method of Math class. We simply ask for 2 user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value which is having a return data type of String thus we have used the Integer.parseInt  to transform it into int. Alternatively if the requirements is to use long then you must use the Long.ParseLong() instead, Double.parseDouble() for double, and Float.parseFloat() for float. This conversion is required because the argument for max() method only accepts either int, long, double or float.

Sample Output

Below is the sample output when you run the above example.

java lang Math max() example output