|
The multiplication and division operators are one of the basic arithmetic operators. They operate mostly the way you expect an arithmetic multiplication and division to take place. They have the higher precedence compared to any other binary operator. Therefore when you execute the following code the multiplication b*a is performed before the addition.
int a = 2, b= 8,c;
c = a + b * a; // The value of c is 18
First, all the operands are evaluated. Therefore, c will be 2 + 8 * 2. Next, the multiplication (8 * 2) takes place because * has higher precedence over +. Then the addition 2 + 16 takes place, and its result is stored in c. Note that you need to know the operator precedence to predict the value of the expression accurately.
The result of multiplication or division may not be always accurate. Sometimes you may loose information if you store result of division in integral types such as int. For instance, the result of division 5/10 is 0.5. However, if you store this result 0.5 in int variable, Java will not store the exact value 0.5 because the int datatype is incapable of storing floating-point values precisely. It will store 0 instead. Note that Java does not flag any error. Following code will compile and run fine:
int result = 5/10;
In some cases, the Java compiler can find out the loss of information or overflow while representing the results of these operations. For instance, if you try to store a bigger result value in a variable that cannot hold that value, you may not get accurate result. In the following code, two byte values 20 and 10 are multiplied. The result will be 200. Since byte value can range only from -128 to +127, you need to store the result in datatype with bigger range such as short.
byte result = 20 * 10; // Error! range for byte value –128 to +127
short widerResult = 20 * 10; // ok
If you use variables to store the operands 20 and 10 instead of literals and then apply the multiplication operator:
int a = 20, b = 10;
short widerResult = a * b; // error!
The compiler will flag an error even if the result is within a range for short variable. This happens because, when any binary operator is applied, the arithmetic promotion (Chapter 10) of operands takes place. Due to it, the a*b will be a multiplication between two int values. and hence compiler complains if you store an int result in smaller data type short.