1

Please consider below code on java:

        long maxDays = 1000;
        maxDays = maxDays * 24;
        maxDays = maxDays * 60;
        maxDays = maxDays * 60;
        maxDays = maxDays * 377;
        System.out.println(maxDays);  // The result is 32572800000

Now I try to do it in one line:

        maxDays = 1000 * 24 * 60 * 60 * 377;
        System.out.println(maxDays);  // The result is -1786938368

Why the result changed !

I think it must be about type conversion from int to long, but I don't know why?

AND how can I do it in one line in correct way?

Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
  • Does this answer your question? [Multiplying long values?](https://stackoverflow.com/questions/1494862/multiplying-long-values) – Sash Sinha Nov 02 '21 at 06:17
  • in the first example at the right of the equation sign you have one long `maxDays`, but in the second, after the equation sign you have 5 int values that will cause `Numeric overflow` exception. you have to define one of the 5 integers as long, lilke: 1000L*24*60*60*377; – Issa Khodadadi Nov 02 '21 at 06:52

1 Answers1

2

You're right: all the numbers (1000, 24, ...) are seen as int and producing an overflow during the calculation. Only the result will be implicitely type casted to long.

To handle the calculation, you can mark all these values as long by adding a L at the end of the number like this:

long maxDays = 1000L * 24L * 60L * 60L * 377L;

Also it would be enough to declare only one number as long like this:

long maxDays = 1000L * 24 * 60 * 60 * 377;
csalmhof
  • 1,820
  • 2
  • 15
  • 24