Java Reference

In-Depth Information

Variable

A variable or anything else, such as an array element, to which a value can be

assigned.

Return type

Just as every operator expects its operands to be of specific types, each operator pro‐

duces a value of a specific type. The arithmetic, increment and decrement, bitwise,

and shift operators return a
double
if at least one of the operands is a
double
. They

return a
float
if at least one of the operands is a
float
. They return a
long
if at

least one of the operands is a
long
. Otherwise, they return an
int
, even if both

operands are
byte
,
short
, or
char
types that are narrower than
int
.

a
x

The comparison, equality, and Boolean operators always return
boolean
values.

Each assignment operator returns whatever value it assigned, which is of a type

compatible with the variable on the left side of the expression. The conditional

operator returns the value of its second or third argument (which must both be of

the same type).

Side efects

Every operator computes a value based on one or more operand values. Some oper‐

ators, however, have
side efects
in addition to their basic evaluation. If an expression

contains side effects, evaluating it changes the state of a Java program in such a way

that evaluating the expression again may yield a different result.

For example, the
++
increment operator has the side effect of incrementing a vari‐

able. The expression
++a
increments the variable
a
and returns the newly incremen‐

ted value. If this expression is evaluated again, the value will be different. The vari‐

ous assignment operators also have side effects. For example, the expression
a\*=2

can also be written as
a=a\*2
. The value of the expression is the value of
a
multi‐

plied by 2, but the expression has the side effect of storing that value back into
a
.

The method invocation operator
()
has side effects if the invoked method has side

effects. Some methods, such as
Math.sqrt()
, simply compute and return a value

without side effects of any kind. Typically, however, methods do have side effects.

Finally, the
new
operator has the profound side effect of creating a new object.

Order of evaluation

When the Java interpreter evaluates an expression, it performs the various opera‐

tions in an order specified by the parentheses in the expression, the precedence of

the operators, and the associativity of the operators. Before any operation is per‐

formed, however, the interpreter first evaluates the operands of the operator. (The

exceptions are the
&&
,
||
, and
?
: operators, which do not always evaluate all their

operands.) The interpreter always evaluates operands in order from left to right.

This matters if any of the operands are expressions that contain side effects. Con‐

sider this code, for example: