BigDecimal.valueOf()


BigDecimal.valueOf()

The BigDecimal class contains an internal cache of frequently used numbers e.g. 0 to 10. The BigDecimal.valueOf() methods are provided in preference to constructors with similar type parameters i.e. in the below example a is preferred to b.

import java.math.BigDecimal;
 
public class BigDecimalExamples {
    public static void main(String[] args) {
        BigDecimal valueA = BigDecimal.valueOf(30L); // Returns cached Object reference
        BigDecimal valueB = new BigDecimal(30L); // Does not return cached Object reference
        BigDecimal valueC = BigDecimal.valueOf(40L); // Does not return cached Object reference
        BigDecimal valueD = new BigDecimal(40L); // Does not return cached Object reference
        BigDecimal valueE = BigDecimal.valueOf(25.25); // Preferred way to convert a double into a BigDecimal
        BigDecimal valueF = new BigDecimal(25.25); // Return unpredictable result
 
        // Displaying the values
        System.out.println("Value A: " + valueA);
        System.out.println("Value B: " + valueB);
        System.out.println("Value C: " + valueC);
        System.out.println("Value D: " + valueD);
        System.out.println("Value E: " + valueE);
        System.out.println("Value F: " + valueF);
    }
}

Initialization of BigDecimals with value zero, one or ten

BigDecimal provides static properties for the numbers zero, one and ten. It's good practise to use these instead of using the actual numbers:

  • BigDecimal.ZERO
  • BigDecimal.ONE
  • BigDecimal.TEN

By using the static properties, you avoid an unnecessary instantiation, also you've got a literal in your code instead of a 'magic number'

//Bad example:
BigDecimal bad0 = new BigDecimal(0);
BigDecimal bad1 = new BigDecimal(1);
BigDecimal bad10 = new BigDecimal(10);
//Good Example:
BigDecimal good0 = BigDecimal.ZERO;
BigDecimal good1 = BigDecimal.ONE;
BigDecimal good10 = BigDecimal.TEN;

BigDecimal objects are immutable

If you want to calculate with BigDecimal you have to use the returned value because BigDecimal objects are immutable:

import java.math.BigDecimal;
 
public class BigDecimalAddition {
    public static void main(String[] args) {
        BigDecimal valueA = new BigDecimal("84.46");
        BigDecimal valueB = new BigDecimal("20.002");
 
        BigDecimal result1 = valueA.add(valueB); // valueA will still be 84.46
        BigDecimal result2 = valueA.add(valueB); // result2 will be 104.462
 
        // Displaying the results
        System.out.println("Result 1: " + result1);
        System.out.println("Result 2: " + result2);
    }
}

Basic Programs