Java Reference
In-Depth Information
EXAMPLE 2-6
Consider the following Java floating-point expressions:
2
12.8 * 17.5 - 34.50
x * 10.5 + y - 16.2
Here, x and y represent variables of the floating-point type; that is, they can hold
floating-point values. (Variables are discussed later in this chapter.)
Evaluating an integral or a floating-point expression is straightforward. As already noted,
when operators have the same precedence, the expression is evaluated from left to right.
To avoid confusion, you can always use parentheses to group operands and operators.
Mixed Expressions
An expression that has operands of different data types is called a mixed expression.A
mixed expression contains both integers and floating-point numbers. The following
expressions are examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 - 13.6 + 18 / 2
In the first expression, the operand + has one integer operand and one floating-point
operand. In the second expression, both operands for the operator / are integers; the first
operand of + is the result of 6 / 4 , and the second operand of + is a floating-point
number. The third example is a more complicated mix of integers and floating-point
numbers. How does Java evaluate such mixed expressions?
Two rules apply when evaluating a mixed expression:
1. When evaluating an operator in a mixed expression:
a. If the operator has the same types of operands (that is, both are integers
or both are floating-point numbers), the operator is evaluated accord-
ing to the type of the operand. Integer operands yield an integer
result; floating-point numbers yield a floating-point number result.
b. If the operator has both types of operands (that is, one is an integer
and the other is a floating-point number), during calculation the
integer is treated temporarily as a floating-point number with the
decimal part of zero, and then the operator is evaluated. The result
is a floating-point number.
2. The entire expression is evaluated according to the precedence rules. The
multiplication, division, and modulus operators are evaluated before the
addition and subtraction operators. Operators having the same level of
precedence are evaluated from left to right. Grouping is allowed for clarity.
 
 
 
Search WWH ::




Custom Search