Mathematical Operations in Java
We have already seen about mathematical calculations in Java. We will now recollect them and then look at a few other aspects which we haven't discussed earlier.
The first thing is regarding the precedence of the five mathematical operators: + - / * and %. /, * and % have a higher precedence than + and -. In order to raise the precedence of a particular operator, we use parentheses. The expression within the parentheses is evaluated before evaluating the rest of the expression. The remainder of the expression is evaluated from left to right. We have seen how the precedence of operators can be raised in the previous example when calculating the average.
double average = ( marks1 + marks2 + marks3 ) / 3.0;
Another important thing is regarding the data type of the result of an operation including two operators and an operand. For example, the result of an expression involving two integers is an integers and not a double. 5/4 gives 1 and not 1.25. The following shows the data type of the result which depends on the data types of the operands.
|Data type returned
||Data type of operands
||Atleast one operand is a double
||Atleast one operand is a float but neither operand is a double
||Atleast one operand is a long but neither operand is a float or a
||Atleast one operand is an int but neither operand is a float, a
double or a long
Consider that we wish to accept two numbers from the user and divide them. Suppose that we store the numbers in num1 and num2, the following expression would not give us the required output:
double result = num1 / num2;
We cannot follow the technique which we have used for the computation of average. There is no way by which we can add a decimal point followed by a zero since we are now dealing with two variables and not constants. The solution lies in casting to a different data type. Casting refers to the conversion of one data type to another data type. We have already seen how we cast data when we were discussing about mathematical operation using byte varaibles. we cast num1 to double and perform the division in the following way.
double result = (double) num1 / num2;