Java Reference
In-Depth Information
combined. If both operands (that is, both numbers) are of type
int
, then the result
of combining them with an arithmetic operator is of type
int
. If one, or both, of
the operands is of type
double
, then the result is of type
double
. For example, if the
variables
baseAmount
and
increase
are both of type
int
, then the number produced
by the following expression is of type
int
:
baseAmount + increase
However, if one, or both, of the two variables is of type
double
, then the result is of
type
double
. This is also true if you replace the operator
+
with any of the operators
−
,
*
,
/
, or
%
.
More generally, you can combine any of the arithmetic types in expressions. If
all the types are integer types, the result will be the integer type. If at least one of the
subexpressions is of a floating-point type, the result will be a floating-point type.
Knowing whether the value produced is of an integer type or a floating-point type
is typically all that you need to know. However, if you need to know the exact type of
the value produced by an arithmetic expression, it can be determined as follows: The
type of the value produced is one of the types used in the expression. Of all the types
used in the expression, it is, with rare exceptions, the last type (reading left to right) on
the following list:
byte
—>
short
—>
int
—>
long
—>
float
—>
double
Here are the rare exceptions: Of all the types used in the expression, if the last type
(reading left to right) is
byte
or
short
, then the type of the value produced is
int
.
In other words, an expression never evaluates to either of the types
byte
or
short
.
These exceptions have to do with an implementation detail that need not concern us,
especially since we almost never use the types
byte
and
short
in this book .
Note that this sequence of types is the same sequence of types we saw when
discussing assignment compatibility. As you go from left to right, the types increase in
the range of values they allow.
4
Parentheses and Precedence Rules
★
If you want to specify exactly what subexpressions are combined with each operator,
you can fully parenthesize an expression. For example,
((base + (rate * hours))/(2 + rate))
If you omit some parentheses in an arithmetic expression, Java will, in effect, put in
parentheses for you. When adding parentheses, Java follows rules called
precedence rules
4
Although we discourage the practice, you can use values and variables of type
char
in arithmetic
expressions using operators such as
+
. If you do so, the
char
values and variables will contribute to
the expression as if they were of type
int
.