### Mixing integer and floating point numbers in an arithmetic operation

• Previously discussed

• Java's automatic floating point conversion in arithmetic expressions:

 All floating point values (float and double) in an arithmetic operation (+, −, *, /) are converted to double type before the arithmetic operation in performed.

• Java's automatic integer conversion in arithmetic operations:

 All integer values (byte, short and int) in an arithmetic operations (+, −, *, /, %) are converted to int type before the arithmetic operation in performed. However, if one of the values in an arithmetic operation (+, −, *, /, %) is long, then all values are converted to long type before the arithmetic operation in performed.

• An very important (but rarely taught) fact about a computer:

 A computer can only operate on data of the same data type

• Mixing integer and floating point numbers in an arithmetic operation

• Java's automatic conversion in a mixed (integer and floating point) arithmetic operation:

 All values in an mixed arithmetic operations (+, −, *, /, %) are converted to double type before the arithmetic operation in performed.

• Important note:

 The conversion rule is applied at the moment that the arithmetic operation is performed

• Example 1:

 ``` int a = 3; double b = 5.0, c; c = a + b; // a (int) is converted to a double // Then the addition is performed (on 2 doubles) ```

• Example 2:

 ``` int a = 5, b = 2; double c = 5.0, d; d = c + a / b; // a/b is performed first. // Because a and b are integers, the division // a/b produces the quotient: a/b = 2 (not 2.5 !!!) // // Next we add: c + 2 // Because c is a double, the integer value 2 // is converted to double 2.0 // Result: 5.0 + 2.0 = 7.0 d = a + c / b; // c/b is performed first. // Because c is doube and Java will convert // b to double, and the division // c/b produces the quotient: c/b = 2.5 ! // // Next we add: a + 2.5 // // Result: 5.0 + 2.5 = 7.5 ```

• Exercise

• What is the type and the value printed by each of the print statements in the following Java program:

 ``` public class Exercise2 { public static void main(String[] args) { short a = 5; int b = 2; double c = 1.0; double d = 5.0; System.out.println( a / b / c ); System.out.println( a / c / b ); System.out.println( a / b ); System.out.println( d / b ); System.out.println( (a + 0) / b ); System.out.println( (d + 0) / b ); System.out.println( (a + 0.0) / b ); System.out.println( (d + 0.0) / b ); } } ```

 ``` a / b / c = 2.0 (double) a / c / b = 2.5 (double) a / b = 2 (int) d / b = 2.5 (double) (a + 0) / b = 2 (int) (d + 0) / b = 2.5 (double) (a + 0.0) / b = 2.5 (double) (d + 0.0) / b = 2.5 (double) ```