1. BigDecimal in Java With Examples
The BigDecimal
class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion, and hashing. It can handle very large and very small floating-point numbers with great precision.
Creating BigDecimal
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
BigDecimal bd1 = new BigDecimal("124567890.0987654321");
BigDecimal bd2 = new BigDecimal("987654321.123456789");
System.out.println("BigDecimal1: " + bd1);
System.out.println("BigDecimal2: " + bd2);
}
}
BigDecimal Operations
import java.math.BigDecimal;
public class BigDecimalOperations {
public static void main(String[] args) {
BigDecimal bd1 = new BigDecimal("124567890.0987654321");
BigDecimal bd2 = new BigDecimal("987654321.123456789");
BigDecimal sum = bd1.add(bd2);
BigDecimal product = bd1.multiply(bd2);
BigDecimal difference = bd1.subtract(bd2);
BigDecimal quotient = bd1.divide(bd2, BigDecimal.ROUND_HALF_UP);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
System.out.println("Difference: " + difference);
System.out.println("Quotient: " + quotient);
}
}
2. BigInteger in Java With Examples
The BigInteger
class is used for mathematical operations involving very large integer calculations that are outside the limit of all available primitive data types.
Creating BigInteger
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger bigInt1 = new BigInteger("123456789012345678901234567890");
BigInteger bigInt2 = new BigInteger("987654321098765432109876543210");
System.out.println("BigInteger1: " + bigInt1);
System.out.println("BigInteger2: " + bigInt2);
}
}
BigInteger Operations
import java.math.BigInteger;
public class BigIntegerOperations {
public static void main(String[] args) {
BigInteger bigInt1 = new BigInteger("123456789012345678901234567890");
BigInteger bigInt2 = new BigInteger("987654321098765432109876543210");
BigInteger sum = bigInt1.add(bigInt2);
BigInteger product = bigInt1.multiply(bigInt2);
BigInteger difference = bigInt1.subtract(bigInt2);
BigInteger quotient = bigInt1.divide(bigInt2);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
System.out.println("Difference: " + difference);
System.out.println("Quotient: " + quotient);
}
}