Let's look at the below code snippet and guess the output

public class LongPuzzle
public static void main(String args[])
long milliSecondsPerDay = 24*60*60*1000;
long microSecondsPerDay = 24*60*60*1000*1000;

What is the result for the above program?

Mathematical computation

We immediately answer the output for this as 1000. But the JVM will give the output for above program as 5.

Why JVM generates output as 5?

Let's analyze the program execution. We've declared two long variables milliSecondsPerDay and microSecondsPerDay and both are being initialized with an integer expression which is evaluated at run time.

Please note that all the numerical expressions in Java are evaluated as integers unless programmers instructs JVM to evaluate expression as long.

The first expression will be evaluated as 86400000 and gets assigned to milliSecondsPerDay. During the second expression evaluation, JVM identifies that the integer range is overflown (Original expression value is 86400000000 but the integer maximum range is 2147483647). So, after all it's bit shifting operations, the evaluated result will be 500654080.

How to fix this?

Instruct JVM to evaluate the expression as a long value. All you've to do is, specify long subscript L for any of the integer value in the expression as below.

long microSecondsPerDay = 24L*60*60*1000*1000;


It is not enough to declare the long data type and assume that everything goes well. When dealing with long values, always make sure you use a suffix L for the integer values.