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.
Previously discussed (cont.) 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.
Previously discussed (cont.) 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: Important note: All values in an mixed arithmetic operations (+, −, *, /, %) are converted to double type before the arithmetic operation in performed. The conversion rule is applied at the moment that the arithmetic operation is performed
Mixing integer and floating point numbers in an arithmetic operation (cont.) Example 1: int a = 3; double b = 4.5, c; c = a + b; // a (int) is converted to a double // Then the addition is performed (on 2 doubles)
Mixing integer and floating point numbers in an arithmetic operation (cont.) Example 2: int a = 5, b = 2; double c = 4.5, 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: = 6.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;
Exercise (cont.) 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 ); }
Exercise (cont.) Answers: 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)
Exercise (cont.) Example Program: (Demo above code) –Prog file: Exercise2.java How to run the program: Right click on link and save in a scratch directory To compile: javac Exercise2.java To run: java Exercise2