I'm trying to do some basic calculation stuff in my android app to compare a Date.getTime()
value with some calculated stuff.
The calculation I do during a database query is:
long minus = pauseDays * 24 * 60 * 60 * 1000;
So basically I calculate the millisecond-value of pauseDays
. If pauseDays
gets bigger (I'm talking about 90 days or so), something strange happens. The result of the calculation is a negative number.
The weird thing is, that the result should be 7776000000
, so it should be way smaller than Long.MAX_VALUE
. Could anybody explain to me why I get a negative number here?
The reason is probably because pauseDays
is an int
type, right? Then you are multiplying it by another bunch of int
s, then converting it to long
.
Consider this:
public class Main {
public static void main(String[] args) {
int pauseDays = 90;
long minus = pauseDays * 24 * 60 * 60 * 1000;
System.out.println(minus);
long pauseDaysL = 90L;
long minusL = pauseDaysL * 24L * 60L * 60L * 1000L;
System.out.println(minusL);
}
}
The output of this is:
-813934592
7776000000
Notice that the first long minus
uses integers to generate its value. The second long minusL
uses all long integer values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With