Things To Remember - Java integer division

  • access_time 8 years ago
  • date_range 19/04/2013
  • comment 0
  • share 0
  • label_outlineJava

Another one which is counterintuitive to people programming in untyped languages while doing Java integer division, is that the result will be integer if both dividend and divisor were integers, regardless of the type of the quotient. See the following test case:

public void shouldShowHowDivisionWorks() {
    int a = 3;
    int b = 5;
    float c = a / b;
    assertEquals(0.0, c, 1e-3); // this is true, but may be unexpected
    c = a / (float) b;
    assertEquals(0.6, c, 1e-3); // this also is true
    c = (float) a / b;
    assertEquals(0.6, c, 1e-3); // this is true too

Last two assertions are correct, because either a or b was cast to float, so the result will always be float too.

Also notice the 1e-3 in last parameter of the assertions. It comes from the fact that when operating on floating values the division result will not always be exact, and there are often round-off errors, and errors due to representation. Therefore comparing two float values for equality is not a good idea, because it depends how they were computed. In my case the result of the division was computed to be 0.6000000238418579. Thus in JUnit the assertEquals takes the delta parameter which tells what is the acceptable difference between compared values (1e-3 or 0.001 here).

Polite Notice - if you have a questions concerning implementation details in your own projects then you're much better off asking them on Stack Overflow. More people to help you this way.