I recently ran into an overflow situation with Java's long data type while multiplying millisecond timestamps. Here is a crib sheet on dealing with large numbers.

Java does not throw a RuntimeException when overflow or underflow occurs but instead silently drops the high-order bits.

The epoch for programming is 1st January 1970. A timestamp returned by System.currentTimeMillis() represents the number of milliseconds that have elapsed since the epoch.

An example timestamp representing the current time (29th September 2011) is

1,317,041,017,000

The limit of a long primitive in Java is 64 bits (2 ^ 64)

2 ^ 64 is 18,446,744,073,709,551,616

Java long is a signed datatype so the largest possible positive value is 2 ^ 63 - 1 and can be conveniently accessed using the constant

Long.MAX_VALUE

Which is

9,223,372,036,854,775,807

In engineering notation http://en.wikipedia.org/wiki/Engineering_notation

Long.MAX_VALUE = 9.2E18

A current timestamp is

1.3E12

Therefore the maximum amount by which you can multiply a millisecond timestamp without overflow is

9.2E18 / 1.3E12 = approimately 7E6

This is approximately 116 seconds worth of milliseconds.

If you need to multiply bigger number than this then use a http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html

## Leave comments, ask questions, or suggest improvements