Java Reference
In-Depth Information
As you might expect, if either or both operands to any numeric operator
are floating point values, the result is a floating point value. However, the
division operator produces results that are less intuitive, depending on the
types of the operands. If both operands are integers, the / operator performs
integer division, meaning that any fractional part of the result is discarded.
If one or the other or both operands are floating point values, the / operator
performs floating point division, and the fractional part of the result is kept.
For example, the result of 10/4 is 2, but the results of 10.0/4 and 10/4.0 and
10.0/4.0 are all 2.5.
A unary operator has only one operand, while a binary operator has two. The
VideoNote
Review of primitive data
and expressions.
+
arithmetic operators can be either unary or binary. The binary versions
accomplish addition and subtraction, and the unary versions represent positive
and negative numbers. For example,
and
-
1 is an example of using the unary negation
operator to make the value negative. The unary
-
operator is rarely used.
Java does not have a built-in operator for raising a value to an exponent.
However, the Math class provides methods that perform exponentiation and many
other mathematical functions. The Math class is discussed in Chapter 3.
+
Operator Precedence
Operators can be combined to create more complex expressions. For example,
consider the following assignment statement:
result = 14 + 8 / 2;
The entire right-hand side of the assignment is evaluated, and then
the result is stored in the variable. But what is the result? If the addi-
tion is performed first, the result is 11 ; if the division operation is
performed first, the result is 18 . The order of operator evaluation
makes a big difference. In this case, the division is performed before
the addition, yielding a result of 18 .
Note that in this and subsequent examples, we use literal values rather than
variables to simplify the expression. The order of operator evaluation is the same
if the operands are variables or any other source of data.
All expressions are evaluated according to an operator precedence hierarchy
that establishes the rules that govern the order in which operations are evaluated.
The arithmetic operators generally follow the same rules you learned in algebra.
Multiplication, division, and the remainder operator all have equal precedence
and are performed before (have higher precedence than) addition and subtraction.
Addition and subtraction have equal precedence.
KEY CONCEPT
Java follows a well-defined set of
precedence rules that governs the
order in which operators will be
evaluated in an expression.
 
Search WWH ::




Custom Search