(Review: ) Is the following correct?
13 * 6 -
No.
The literals (the integers) and the operators are out of order in the
above incorrect expression.
(One legal arrangement is
13 * -6
for 13 times minus 6.)
An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value.
Expressions contain operators and
operands.
You already know what an operator is
(a symbol such as +
, -
,
*
, or /
that calls for an arithmetic operation).
An operand is a value that is acted upon by an operator.
The parts of an expression must be arranged correctly. The syntax of Java describes the correct arrangements. The rules for correct Java expressions are nearly the same as for algebra:
*
, Division /
,
Addition +
, Subtraction -
should have two operands, one on each side.-
and unary plus +
should be followed by one operand.()
can surround a legal expression to make it an operand.
In 13 - 5
the 13 and the 5 are the operands and
the -
is the operator.
In Java expressions, operators and operands must be explicit.
In 14*sum
14 and sum are the operands.
The star for multiplication must be present.
The expression 14sum
is incorrect.
In a correct expression, parentheses will always be balanced. Parentheses are balanced when they form matching pairs. Each left parenthesis has a matching right parenthesis. Pairs of parentheses can be nested within other pairs.
For example, the following are balanced:
( )
( ( ) ( ) )
( ( ) ) ( )
( ) ( ( )( ) ) ( )
The following are NOT balanced:
(
( ( ( ) )
( ( ) ) ( ))
( ) ( )( ) ) ( )
The details of expression syntax are in the Java documentation, should you care to dig through it. The best way to learn these rules is to study some examples.
Which minus sign in the following stands for "subtraction" and which stands for "negation"?
-23 - 3