0
public class PragsLongDivision{

public static void main (String [] args){
 final long MICRO_PER_DAY=24 * 60 * 60 * 1000 * 1000;
 final long MILLIS_PER_DAY= 24 * 60 * 60 * 1000;

  System.out.println(MICRO_PER_DAY / MILLIS_PER_DAY  );

   }
}

This program print 5 why? Please share best salutation with reason.

Prags
  • 2,457
  • 2
  • 21
  • 38
  • Take a look at https://stackoverflow.com/questions/3144610/integer-division-how-do-you-produce-a-double – George Z. Jan 05 '19 at 11:19

1 Answers1

0

In these lines:

 final long MICRO_PER_DAY=24 * 60 * 60 * 1000 * 1000;
 final long MILLIS_PER_DAY= 24 * 60 * 60 * 1000;

each of the constant integer numbers is of type int and the result calculated is also of type int.
But the result you would expect: 86400000000 for MICRO_PER_DAY is too large to fit in the 32 bits of an int and it is truncated.
This is called Numeric Overflow.
To get the right result use this:

 final long MICRO_PER_DAY=24L * 60 * 60 * 1000 * 1000;
 final long MILLIS_PER_DAY= 24L * 60 * 60 * 1000;

The L suffix after 24 will guide the compiler so that it does store the result in the 64 bits of type long and not truncate it.

forpas
  • 160,666
  • 10
  • 38
  • 76
  • It is not really about storing the result as a long that makes this work: it is that the calculation is performed using longs. A consequence is that you need to store the result as a long, but that is not the main reason. – Andy Turner Jan 05 '19 at 11:38
  • *that the calculation is performed using longs* each calculation produces a result that is stored as long. *but that is not the main reason* what does this mean? – forpas Jan 05 '19 at 11:42
  • `long a = Integer.MAX_VALUE * Integer.MAX_VALUE;` *stores* the result as a long, but *calculates* it with ints. – Andy Turner Jan 05 '19 at 11:55
  • `long a = Integer.MAX_VALUE * Integer.MAX_VALUE;` **finally** stores the result inside the 64 bits of a long, but this result is calculated as `int` and this is why it is wrong. – forpas Jan 05 '19 at 12:00