Creation and initialization of BigDecimal objects

The BigDecimal class in Java is designed for precise representation and computation of decimal numbers. One of the most important aspects of using BigDecimal correctly is understanding how to create and initialize its objects. Improper initialization (especially using double) can lead to unexpected precision errors.

Constructors

Program

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

public class BigDecimalDemo {
    public static void main(String[] args) {
        
        // --- Using Constructors ---
        
        // 1. Constructor with String (Recommended)
        BigDecimal bd1 = new BigDecimal("123.45");
        System.out.println("Constructor with String: " + bd1);

        // 2. Constructor with int
        BigDecimal bd2 = new BigDecimal(100);
        System.out.println("Constructor with int: " + bd2);

        // 3. Constructor with long
        BigDecimal bd3 = new BigDecimal(123456789L);
        System.out.println("Constructor with long: " + bd3);

        // 4. Constructor with BigInteger
        BigInteger bigInt = new BigInteger("99999");
        BigDecimal bd4 = new BigDecimal(bigInt);
        System.out.println("Constructor with BigInteger: " + bd4);

        // 5. Constructor with String and MathContext
        BigDecimal bd5 = new BigDecimal("123.45678", new MathContext(5));
        System.out.println("Constructor with String and MathContext: " + bd5);

        // 6. Constructor with double (Not Recommended)
        BigDecimal bd6 = new BigDecimal(0.1); // may result in unexpected value
        System.out.println("Constructor with double (Not Recommended): " + bd6);
        
        // --- Using Static Methods ---
        
        // 7. valueOf(double) — Recommended over constructor
        BigDecimal bd7 = BigDecimal.valueOf(0.1);
        System.out.println("valueOf(double): " + bd7);

        // 8. valueOf(long)
        BigDecimal bd8 = BigDecimal.valueOf(100L);
        System.out.println("valueOf(long): " + bd8);

        // 9. valueOf(long, int)
        BigDecimal bd9 = BigDecimal.valueOf(12345L, 2); // creates 123.45
        System.out.println("valueOf(long, int): " + bd9);
        
        // Sample arithmetic using these objects
        BigDecimal result = bd1.add(bd9);
        System.out.println("Sum of bd1 and bd9: " + result);
    }
}

/*
Constructor with String: 123.45
Constructor with int: 100
Constructor with long: 123456789
Constructor with BigInteger: 99999
Constructor with String and MathContext: 123.46
Constructor with double (Not Recommended): 0.10000000000000000555
valueOf(double): 0.1
valueOf(long): 100
valueOf(long, int): 123.45
Sum of bd1 and bd9: 246.90
*/
Scroll to Top