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?

Answers


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.


Need Your Help

IntelliJ Split Window Navigation

intellij-idea

If I split the editor window (horizontal or vertical) into N tab groups, how do I switch/toggle from one tab group to another via the keyboard? If all of the tabs are in the same group you can swi...

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

javascript jquery django datepicker

I found few answers on stack overflow but still cant resolve my problem.