Java math question, great result!

Why are the results different for the first and first? I guess this is due to the limit for the long type.

long seconds = System.currentTimeMillis();
long first = (seconds / (1000*60*60*24))/365;
long first1 = seconds / (1000*60*60*24*365);
System.out.println(first); 
System.out.println(first1);

Thank!

+3
source share
2 answers

The denominator of the second overflows type int.

It makes no difference if you do it like this: use long letters:

public class Overflow
{
    public static void main(String[] args)
    {
        long seconds = System.currentTimeMillis();
        long first = (seconds / (1000L * 60L * 60L * 24L)) / 365L;
        long i = 1000L * 60L * 60L * 24L * 365L;
        long first1;
        first1 = seconds / i;
        System.out.println(i);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(first);
        System.out.println(first1);
        System.out.println(first1/first);
    }
}
+5
source

This is because in the first you divide by an int, which is truncated and then divide by another int.

In the second, you just divide by int.

+10
source

Source: https://habr.com/ru/post/1773417/


All Articles