Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^108) | Arithmetic Expressions
the following are appropriate assignment statements:
Variable Expression
alpha = 2856;
rate = 0.36;
ch = 'B';
num = alpha;
In each of these assignment statements, the data type of the expression matches the data
type of the variable to which it is assigned. Later in this chapter, we will see what happens
when the data types do not match.


3.4 Simple Arithmetic Expressions


Now that we have looked at declarations and assignments, we can consider how to use val-
ues of numeric types in our calculations. Calculations are performed with expressions. Here
we look first at simple expressions that involve at most one operator so that we may exam-
ine each operator in detail. Then we move on to compound expressions that combine mul-
tiple operations.

Arithmetic Operators


Expressions are made up of constants, variables, and operators. The following are all valid
expressions:

alpha + 2 rate – 6.0 4– alpha rate alpha * num

The operators allowed in an expression depend on the data types of the constants and
variables in the expression. The arithmetic operatorsare

+ Unary plus


  • Unary minus



  • Addition



  • Subtraction



  • Multiplication


/ { Floating-point division (floating-point result)


Integer division (no fractional part)
% Modulus (remainder from division)
The first two operators are unary operators—they take just one operand. The last
five are binary operators—they take two operands. Unary plus and minus are used
as follows:

–54 +259.65 -rate

Unary operator An operator
that has just one operand
Binary operator An operator
that has two operands
Free download pdf