What is the BigDecimal.max() method in Java?

BigDecimal is an immutable, arbitrary-precision signed decimal number. BigDecimal contains an arbitrary precision integer unscaled value and a 32-bit integer scale. For example, in the value 10.11, 1011 is the unscaled value and 2 is the scale. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Read more about the BigDecimal class here.

The max method of the BigDecimal class returns the maximum of the current object and the passed argument.

Syntax

public BigDecimal max(BigDecimal val)

Parameters

The max method takes a BigDecimal object as a parameter.

Return value

  • If the parameter passed is greater than the current object value, then the max method returns the parameter. Otherwise, it returns the current object.

  • If the parameter and current object are equal, then max returns either one.

Code

The example below demonstrates how to use the max method.

import java.math.BigDecimal;
class BigDecimalMaxExample {
public static void main( String args[] ) {
BigDecimal val1 = new BigDecimal("99.01");
BigDecimal val2 = new BigDecimal("99.022");
BigDecimal result = val1.max(val2);
System.out.println(result);
}
}

Explanation

In the code above, we do the following:

  • Import the BigDecimal class.

  • Create two BigDecimal objects, val1 with value 99.01 and val2 with value 99.022.

  • Call the max method on the val1 object with val2 as an argument. This method call will return the val2 object as a result because val2 > val1.

Free Resources