BigInteger Vs BigDecimal Java

BigInteger Vs BigDecimal Java:

Integer:

Integer is a wrapper class of primitive data type int. At the max integer can store the 10-digit value. [1234567890].

[plain]

int a = 1234567890; [compile]

int b = 12345678901; [wont compile, "The literal 12345678901 of type int is out of range" error]

[/plain]

Long:

Long is a wrapper class of primitive data type long. At the max Long can store 19-digit value. [1234567890123456789L].

[plain]

Long a = 1234567890123456789L; [Compile]

Long b= 12345678901234567890L; [wont compile, "The literal 12345678901234567890L of type long is out of range" error]

[/plain]

 

When we need BigInteger ?

If you want to store more than 19-digit number then we need BigInteger.

[plain]

BigInteger bi1 = new BigInteger("123456789012345678901234567890");

add(BigInteger ), subtract(BigInteger ), multiply(BigInteger ),divide(BigInteger )  can be used to perform the arithmetic operations with BigInteger numbers.

[/plain]

 

 

BigDecimal:

Its like BigInteger only, but the value will be floating value.

[plain]

BigDecimal bd1 = new BigDecimal("91.333333333333333333333333333");
BigDecimal bd2 = new BigDecimal("9.666666666666666666666666667");
System.out.println(bd1.add(bd2));

[/plain]

 

Will print the “101.000000000000000000000000000“.

 

 

Recommended Java Books:

 

 

Leave a Reply