Java Reference

In-Depth Information

1.
int
expression
2+3
is evaluated to yield the expression
5+4*5.2
.

2.
4
is converted to the
double
value
4.0
, and
4.0 * 5.2
is evaluated to

yield the expression
5 + 20.8
.

3.
5
is converted to the
double
value
5.0
and the addition is performed to

yield the value
25.8
.

This conversion of value from type
int
to type
double
happens automati-

cally; you do not have to worry about it. But, if you want, you can explicitly

request such a conversion, or
cast
as it is called in Java, by preceding the value

to be converted by the cast
(
double
)
. (This “type cast” is actually another oper-

ator!) Here is an example:

5/(
double
)2

is evaluated as follows:

1. The value
2
is cast to type
double
, yielding the expression
5 / 2.0
.

2. The value
5
is converted to
double
, yielding the expression
5.0 / 2.0
.

3.
double
division is performed, yielding the
double
value
2.5
.

Order of operations is important: to evaluate
(
double
)(5/2)
do the divi-

sion in
int
arithmetic, yielding
2
, and then cast
2
to
double
to yield
2.0
.

You can also cast
double
values to type
int
, using
(
int
)
. In the expression

below, all operations are performed in
double
arithmetic, and then the result is

cast to an
int
:

(
int
) ((3.5 + 4.6) / 21.2)

When casting to an
int
, the value is truncated toward zero, so
(
int
) 3.9
eval-

uates to
3
and
(
int
) -3.9
evaluates to
-3
. Casts from
double
to
int
are not per-

formed automatically because they can lose information.

We say that type
int
is
narrower
than type
double
and type
double
is
wider

than type
int
because every
int
value is a
double
but not the other way around.

A cast from
int
to
double
is called a
widening cast
, and a cast from
double
to

int
is called a
narrowing cast
. Java performs widening casts implicitly, when

required, but narrowing casts must be explicitly given in order to be performed.

1.1.4

Type boolean and arithmetic relations

Another type that you will use frequently is
boolean
(named after George Boole,

a nineteenth-century mathematician who was one of the parents of logic). Type

boolean
has only two values:
true
and
false
.

In Java, there are three operations on
boolean
values. We describe them

assuming that
b1
and
b2
are
boolean
expressions (their precedences are given

later):

Lesson

page 6-6

•

Negation, or
not
:
!b1

Expression
!b1
evaluates to
true
if
b1
is
false
and
false
otherwise.

Search WWH ::

Custom Search