Mathematical operations in Java
This section looks at how to perform various types of calculation in Java.
Depending on your needs, there are essentially two "frameworks" for doing calculations:
- for most "everyday" calculations, Java's built-in primitive types provide
the fastest, simplest solution: operations on ints, longs,
floats, doubles are straightforward to program
and generally map directly on to low-level processor
instructions, allowing most to complete in the order of a nanosecond with any stored
numbers taking up a few bytes of memory;
- for special cases, the BigInteger and BigDecimal classes
allow decimal numbers with an arbitrary number of digits to be stored and calculated
on, up to the limits of available memory; the time and memory requirements then depend
more heavily on the operation being performed and the number of digits involved, and the
code involved can be a little clumsier.
Calculations with primitive types
On the next and subsequent pages, we look at floating point
primitive operations in Java: that is, operations on the float and double
Calculations with BigInteger and BigDecimal
For more specialist applications, we later look at the BigInteger
and BigDecimal classes, which allow representation of— and calculations on— numbers with an arbitrary
number of digits. We include a look at the performance
of BigInteger/BigDecimal operations, in particular an analysis of the
performance of multiplication.