I have a simple timestamp based expression which extracts value from JSONObject. The following is an excerpt of the code,
Long cur_trig = Long.parseLong(api_content.get("timestamp").toString());
Long last_trig = Long.parseLong(trigger_info.get(key));
frequency = 60.0
if ( last_trig + frequency*1000 > cur_trig) {
System.out.println("Too early for an alert");
}
The above code will not satisfy the if
condition, even if it's theoretically true.
Long curr_trig = 1455213601000L;
Long last_trig = 1455213600000L;
double freq = 60.0;
if (last_trig + freq * 1000 > curr_trig) {
System.out.println("Yup its correct");
}
In this case, it works perfectly fine. I have manually printed the values in the first case and the numbers do add up. The weird thing, I noticed that, if I manually typecast the values:
Long next_trig_time = (long) (last_trig + alert.frequency*1000);
if ( next_trig_time > cur_trig) {
System.out.println( "Its fine!");
}
This seems to work fine. What I fail to understand is, should Java automatically typecast the values to higher data type while evaluating an expression? Or atleast throw a warning / error?
Edit 1: Based on suggestions, I added the following
boolean notified = last_trig + alert.frequency*1000 > cur_trig ;
if (notified) {
System.out.println( "Its fine!");
}
This doesn't make any difference compared to the first case.
Edit 2:
Using long
instead of Long
:
long last_trig = Long.parseLong(trigger_info.get(key));
long cur_trig = Long.parseLong(api_content.get("timestamp").toString());
frequency = 60.0
boolean notified = last_trig + frequency*1000 > cur_trig ;
if (notified) {
System.out.println( "Its fine!");
}
Surprisingly, even this ain't working.
Edit 3: Here is a reproducible issue
JSONObject js = new JSONObject();
js.put("last_trig","1455213601000");
js.put("cur_trig", "1455213600000");
Long last_trig = Long.parseLong(js.get("last_trig").toString());
Long cur_trig = Long.parseLong(js.get("cur_trig").toString());
float frequency = (float) 60.0;
Long next_trig_time = (long) (last_trig + frequency*1000);
if (last_trig + frequency*1000 > cur_trig) {
System.out.println("[Case 1] Too early for an alert");
}
else {
System.out.println("[Case 1] Too late for an alert");
}
if ( next_trig_time > cur_trig) {
System.out.println("[Case 2] Too early for an alert");
}
else {
System.out.println("[Case 2] Too late for an alert");
}
Current output:
[Case 1] Too late for an alert
[Case 2] Too early for an alert
Expected output:
[Case 1] Too early for an alert
[Case 2] Too early for an alert