Home > other >  Why adding value to a long variable make it lower?
Why adding value to a long variable make it lower?

Time:03-09

look at the following code please (I am trying to add 30 days to System.currentTimeMillis):

    int days = 30;
    long a = System.currentTimeMillis();
    long b = a   (days * 24 * 60 * 60 * 1000);

According to the time I run the code, it was the result:

a = 1646737213282 , b = 1645034245986

Why b is smaller than a ?

CodePudding user response:

The issue is that the int range is being exceeded. The max int range is from

-2,147,483,648 (-231) to 2,147,483,647 (231-1)

When you multiply, it is stored as a int. But, that's not the limit. So, the solution will be to parse it to a long. You can check out my code below:

int days = 30;
long a = System.currentTimeMillis();
long b = a   ((long)days * 24 * 60 * 60 * 1000);
System.out.println("a = "   a   "       b = "   b);
  • Related