Java Reference
In-Depth Information
number1
45
number2
72
sum
117
Fig. 2.10
|
Memory locations after storing the sum of
number1
and
number2
.
Most programs perform arithmetic calculations. The
arithmetic operators
are summa-
rized in Fig. 2.11. Note the use of various special symbols not used in algebra. The
asterisk
(
*
) indicates multiplication, and the percent sign (
%
) is the
remainder operator
, which
we'll discuss shortly. The arithmetic operators in Fig. 2.11 are
binary
operators, because
each operates on
two
operands. For example, the expression
f
+
7
contains the binary op-
erator
+
and the two operands
f
and
7
.
Java operation
Operator
Algebraic expression
Java expression
Addition
+
f
+ 7
f + 7
Subtraction
-
p
-
c
p - c
Multiplication
*
bm
b * m
--
÷
Division
/
x
/
y
or
or
x
y
x / y
Remainder
%
r
mod
s
r % s
Fig. 2.11
|
Arithmetic operators.
Integer division
yields an integer quotient. For example, the expression
7
/
4
evaluates
to
1
, and the expression
17
/
5
evaluates to
3
. Any fractional part in integer division is
simply
truncated
(i.e.,
discarded
)—no
rounding
occurs. Java provides the remainder oper-
ator,
%
, which yields the remainder after division. The expression
x
%
y
yields the remainder
after
x
is divided by
y
. Thus,
7
%
4
yields
3
, and
17
%
5
yields
2
. This operator is most com-
monly used with integer operands but it can also be used with other arithmetic types. In
this chapter's exercises and in later chapters, we consider several interesting applications of
the remainder operator, such as determining whether one number is a multiple of another.
Arithmetic Expressions in Straight-Line Form
Arithmetic expressions in Java must be written in
straight-line form
to facilitate entering
programs into the computer. Thus, expressions such as “
a
divided by
b
” must be written
as
a
/
b
, so that all constants, variables and operators appear in a straight line. The follow-
ing algebraic notation is generally not acceptable to compilers:
a
--