Java Reference
In-Depth Information
Similarly, the
--
operator decrements its single numeric operand, which must be a
variable, an element of an array, or a field of an object, by one. Like the
++
operator,
the behavior of
--
depends on its position relative to the operand. When used
before the operand, it decrements the operand and returns the decremented value.
When used after the operand, it decrements the operand, but returns the
undecre‐
mented
value.
The expressions
x++
and
x--
are equivalent to
x=x+1
and
x=x-1
, respectively, except
that when using the increment and decrement operators,
x
is only evaluated once. If
x
is itself an expression with side effects, this makes a big difference. For example,
these two expressions are not equivalent:
a
[
i
++]++;
// Increments an element of an array
// Adds 1 to an array element and stores new value in another element
a
[
i
++]
=
a
[
i
++]
+
1
;
These operators, in both prefix and postfix forms, are most commonly used to
increment or decrement the counter that controls a loop.
Comparison Operators
The comparison operators consist of the equality operators that test values for
equality or inequality and the relational operators used with ordered types (num‐
bers and characters) to test for greater than and less than relationships. Both types
of operators yield a
boolean
result, so they are typically used with
if
statements and
while
and
for
loops to make branching and looping decisions. For example:
if
(
o
!=
null
)
...;
// The not equals operator
while
(
i
<
a
.
length
)
...;
// The less than operator
Java provides the following equality operators:
Equals (
==
)
The
==
operator evaluates to
true
if its two operands are equal and
false
otherwise. With primitive operands, it tests whether the operand values them‐
selves are identical. For operands of reference types, however, it tests whether
the operands refer to the same object or array. In other words, it does not test
the equality of two distinct objects or arrays. In particular, note that you cannot
test two distinct strings for equality with this operator.
If
==
is used to compare two numeric or character operands that are not of the
same type, the narrower operand is converted to the type of the wider operand
before the comparison is done. For example, when comparing a
short
to a
float
, the
short
is first converted to a
float
before the comparison is per‐
formed. For floating-point numbers, the special negative zero value tests equal
to the regular, positive zero value. Also, the special NaN (Not-a-number) value
is not equal to any other number, including itself. To test whether a floating-
point value is NaN, use the
Float.isNan()
or
Double.isNan()
method.