Expressions and Arithmetic Operators
Read this chapter, which discusses arithmetic operations in greater detail along with solving expressions with mixed data types.
2. Expressions
Answer:
No.
Expressions
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.)
Expressions contain operators and operands. You already know what an operator is (a symbol such as +
, -
, *
, or /
that calls
for an arithmetic operation).
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:
-
Each operator must have the correct number of operands.
- Multiplication
*
, Division/
, Addition+
, Subtraction-
should have two operands, one on each side. - Negation
-
and unary plus+
should be followed by one operand.
- Multiplication
- Parentheses
()
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 are balanced. Parentheses are balanced when they form matching pairs. Each left parenthesis has a matching right parenthesis. Balanced pairs of parentheses can be nested within other balanced 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.
Question 2:
Which minus sign in the following stands for "subtraction" and which stands for "negation"?
-23 - 3