Core Java || BigInteger & BigDecimal
1 min readJul 15, 2023
In Java,BigInteger
& BigDecimal
and are classes in the java.math
package that provides arbitrary-precision integer and arbitrary-precision decimal, respectively.
They are used when working with extremely large or precise numeric values that exceed the capabilities of the primitive data types (double
, float
, long
, etc.).
BigInteger: -
BigInteger
is useful in scenarios such as cryptography, number theory, large calculations, or whenever precise integer arithmetic is required.
import java.math.BigInteger;
BigInteger num1 = new BigInteger("12345678901234567890");
BigInteger num2 = new BigInteger("98765432109876543210");
BigInteger sum = num1.add(num2);
BigInteger difference = num1.subtract(num2);
BigInteger product = num1.multiply(num2);
BigInteger quotient = num1.divide(num2);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
BigDecimal: -
BigDecimal
is commonly used in financial applications, currency conversions, tax calculations, scientific computations, or any scenario where accuracy and precision in decimal arithmetic are critical.
import java.math.BigDecimal;
BigDecimal num1 = new BigDecimal("1234.56");
BigDecimal num2 = new BigDecimal("7890.12");
BigDecimal sum = num1.add(num2);
BigDecimal difference = num1.subtract(num2);
BigDecimal product = num1.multiply(num2);
BigDecimal quotient = num1.divide(num2, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);