Java double type unintended integer division

Question

What is the output of the following code?


public class Main {
  public static void main(String[] args) {
    int number1 = 1;
    int number2 = 2;
    double average = (number1 + number2) / 2;
    System.out.println(average);/*from  w  w w  .j a v  a2 s . co m*/
    average = (number1 + number2) / 2.0;
    System.out.println(average);
  }
}


1.0
1.5

Note

Java uses the same divide operator / to perform both integer and floating-point division.

When two operands are integers, the / operator performs an integer division.

The result of the operation is an integer.

The fractional part is truncated.

To force two integers to perform a floating-point division, make one of the integers into a floating-point number.




PreviousNext

Related