Reputation: 45515
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?
Upvotes: 1
Views: 134
Reputation: 1860
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;
Upvotes: 2