Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
BigNumbers
-
ints only have a limited storage capacity, and floats and doubles are not
100% precise. There has to be an alternative!
-
There is, but it is slower. BigInteger stores large numbers, BigDecimal
accurately stores numbers with decimals.
-
But there are drawbacks:
-
Computations are somewhat slower.
-
You cannot use normal operators.
-
To declare a BigInteger:
-
BigInteger myDesiredSalary = BigInteger.valueOf(10000000000000);
-
BigInteger myDesiredSalary = new BigInteger("100000000000");
-
The declarations are similar for BigDecimals.
-
To add two BigIntegers:
-
BigInteger newSalary = myDesiredSalary.add(new BigInteger("1000000000"));
-
Multiplication, division, and subtraction can be performed with multiply(BigInteger
a); divide(BigInteger a); and subtract(BigInteger a); respectively.
-
Again, BigDecimal is similar.
-
Look like a lot of work?
-
Yes, but wait until you have an integer overflow error, or totals that
are off by a cent! It will drive you nuts. I speak from experience
here!
Lab Time


Created by: Brandan
Jones January 4, 2002