Java Reference
In-Depth Information
Following these rules, when you evaluate a mixed expression, you concentrate on one
operator at a time, using the rules of precedence. If the operator to be evaluated has operands
of the same data type, evaluate the operator using Rule 1(a). That is, an operator with integer
operands yields an integer result, and an operator with floating-point operandsyieldsafloating-
point result. If the operator to be evaluated has one integer operand and one floating-point
operand, before evaluating this operator, you treat the integer operand as a floating-point
number with a decimal part of zero. Example 2-7 shows how to evaluate mixed expressions.
EXAMPLE 2-7
Mixed Expression
Evaluation
Rule Applied
3 / 2 = 1 (integer division; Rule 1(a))
3 / 2 + 5.0
= 1 + 5.0
(1 + 5.0 = 1.0 + 5.0 (Rule 1(b))
= 6.0)
= 6.0
15.6 / 2 = 15.6 / 2.0 (Rule 1(b))
= 7.8
15.6 / 2 + 5
= 7.8 + 5
= 7.8 + 5.0 (Rule1(b))
= 12.8
= 12.8
7.8 + 5
= 5.0 / 2.0 (Rule 1(b))
= 2.5
4 + 5 / 2.0
= 4 + 2.5
5 / 2.0
= 4.0 + 2.5 (Rule 1(b))
= 6.5
= 6.5
4 + 2.5
4 * 3 = 12; (Rule 1(a))
4 * 3 + 7 / 5 - 25.5
= 12 + 7 / 5 - 25.5
7 / 5 = 1 (integer division; Rule 1(a))
= 12 + 1 - 25.5
12 + 1 = 13; (Rule 1(a))
= 13 - 25.5
13 - 25.5 = 13.0 - 25.5 (Rule 1(b))
= -12.5
= -12.5
The following Java program evaluates the preceding expressions:
// This program illustrates how mixed expressions are evaluated.
public class Example2_7
{
public static void main(String[] args)
{
System.out.println("3 / 2 + 5.0 = " + (3 / 2 + 5.0));
System.out.println("15.6 / 2 + 5 = " + (15.6 / 2 + 5));
System.out.println("4 + 5 / 2.0 = " + (4 + 5 / 2.0));
System.out.println("4 * 3 + 7 / 5 - 25.5 = "
+ (4 * 3 + 7 / 5 - 25.5));
}
}
Search WWH ::




Custom Search