Java Reference
In-Depth Information
lhs = lhs op (rhs);
The right-hand side (
rhs
) is in brackets because it is worked out first — then the result is combined with
the left-hand side (
lhs
) using the operation
op
. Let's look at a few examples of this to make sure it's clear.
To increment an
int
variable
count
by 5 you can write:
count += 5;
This has the same effect as the following statement:
count = count + 5;
Of course, the expression to the right of the
op=
operator can be anything that is legal in the context, so
the statement
result /= a % b/(a + b);
is equivalent to
result = result/(a % b/(a + b));
What I have said so far about
op=
operations is not quite the whole story. If the type of the result of the
rhs
expression is different from the type of
lhs
, the compiler automatically inserts a cast to convert the
rhs
value to the same type as
lhs
. This would happen with the last example if
result
was of type
int
and
a
and
b
were of type
double
, for example. This is quite different from the way the normal assignment operation is
treated. A statement using the
op=
operator is really equivalent to:
lhs = (type_of_lhs)(lhs op (rhs));
The automatic conversion is inserted by the compiler regardless of what the types of
lhs
and
rhs
are.
Of course, this can result in information being lost due to the cast, and you get no indication that it has oc-
curred. This is different from ordinary assignment statements where an automatic cast is allowed only when
the range of values for the type of
lhs
is greater that the range for the type of
rhs
.
The complete set of
op=
operators are the following:
You will learn about the operators on the second row later in the topic.
MATHEMATICAL FUNCTIONS AND CONSTANTS
Sooner or later you are likely to need mathematical functions in your programs, even if it's only to obtain
an absolute value or calculate a square root. Java provides a range of methods that support such functions
as part of the standard library that is stored in the package
java.lang
, and all these are available in your
program automatically.
The methods that support various additional mathematical functions are implemented in the
Math
class as
static methods, so to reference a particular function you can just write
Math
and the name of the method you