Java Reference

In-Depth Information

2147483649
, but in Java it evaluates to
-2147483647
!

Integer.MAX_VALUE + 2
overflow occurs!

In your first programs, overflow will not be an issue. Just be aware that

expressions in Java yield a value that is determined by the type of the expression,

and if you try to produce a number outside the range of that type, overflow

occurs and your answers are probably not correct.

Integer division

Division, as in
7/2
, yields a value of type
int
. Hence, the value of
7/2

cannot be
3.5
. Instead, the value is truncated toward
0
to produce an
int
:

7/2
has the value
3

-7 / 2
has the value
-3

This will seem strange at first, but you will get used to it. Just remember that,

because Java expressions are defined in the context of being evaluated on a com-

puter, within Java programs (and indeed most programming languages), the rules

are slightly different from conventional mathematics.

Finding out more about type int and its relation to other Java types

This section is a brief introduction to type
int
. It does not discuss its rela-

tion to other types that deal with integers. This introduction should satisfy your

needs for weeks to come. However, at some point you should investigate such

“integral types”. Chapter 6 contains a complete discussion of such types and

should be used as a reference.

1.1.2

Type double

Numbers written with a decimal point are of type
double
. Here are examples:

Lesson page

6-3

5. 4.3 .00000001

Java uses
scientific notation
to make
double
numbers like the rightmost one on

the line above easier to read. The rightmost number can be written as:

1E-8

Here,
E
stands for “exponent”, and the integer following it indicates how many

places to move the decimal point —in this case,
8
decimal places to the left. The

corresponding mathematical
scientific notation
would be
1*10
-8
. As another

example,
0.05E6
is equal to
50000
: the
E6
indicates to move the decimal point

6
places to the right.

Think about
double
values as approximations to the “real numbers”. They

are approximations because the number of digits that can be used is finite, while

a real number can have an infinite number of digits. For example, the fraction

1/3
is
0.33333...
, where the dots
...
represent an infinite number of
3
s. But

Tip:
See the

ProgramLive

glossary for a

definition of

scientific nota-

tion.

Search WWH ::

Custom Search