user1515310
user1515310

Reputation: 95

Android / Java: long gets negative without exceeding max_value

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?

Upvotes: 9

Views: 3214

Answers (1)

Cat
Cat

Reputation: 67502

The reason is probably because pauseDays is an int type, right? Then you are multiplying it by another bunch of ints, 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.

Upvotes: 22

Related Questions