Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java simple math anomaly

Tags:

java

Consider the simple code

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Main {


    public static void main(String args[]){
        System.out.println(isFresh("2013-03-26 06:25:34"));
    }

    private static boolean isFresh(String ts){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        Date date = new Date();
        try {
            date = sdf.parse(ts);

            if(( new Date().getTime() - date.getTime())>(24*40*60*60*1000)){ //Ignore events before 40 days. 
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}

Now, the program prints True if I run it. But if I replace 24*40*60*60*1000 with 3456000000.0 it returns False. Note that I am appending a .0 at the end so that Java treats it as a double instead of int. int can not take that large number but double can.

Why is that ? I suspect this has something to do the way numbers are represented internally.

like image 1000
Akshar Prabhudesai Avatar asked Nov 29 '25 12:11

Akshar Prabhudesai


1 Answers

You are hitting integer overflow with 24*40*60*60*1000. When you use 3456000000.0 there is no overflow because, as you say, it's a double. Hence the different result.

We can avoid the overflow using doubles:

24.0 * 40.0 * 60.0 * 60.0 * 1000.0

or longs:

24L * 40L * 60L * 60L * 1000L
like image 149
Daniel Lubarov Avatar answered Dec 01 '25 02:12

Daniel Lubarov