Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.2 Numeric Data Types | 103

old object remains unchanged. It’s like when you move to a new house or apartment. Your
old residence still exists, but you go home to the new place each day. To stretch this analogy
a bit farther, if no one else is living in your old residence, and it remains abandoned for long
enough, it may be demolished and the land reused. The same thing happens in Java. If no vari-
able refers to an object, then eventually the JVM notices this lack of a reference and reclaims
its memory space so that it can be reused.
The name “reference,” by the way, comes from the fact that the contents of a reference
variablereferto another place in memory. You can also think of a reference type as being
analogous to the call number of a library book. Armed with the call number, you can go
into the library and find the book. If a friend wants to find the same book, you can give a
copy of the call number to him or her, which is much easier than giving your friend a copy
of the book.
Do not feel overwhelmed by the quantity of data types shown in Figure 3.1. Its purpose
is simply to give you an overall picture of what is available in Java. Except for the Stringand
I/O classes, this chapter focuses mainly on the primitive types. First we look at the primitive
integral types (used primarily to represent integers), and then we consider the floating-point
types (used to represent real numbers containing decimal points). We postpone detailed
coverage of the remaining primitive type,boolean, until Chapter 4.


3.2 Numeric Data Types


You already are familiar with the basic concepts of integers and real numbers in mathe-
matics. However, as used on a computer, the corresponding data types have certain limita-
tions, which we now examine.


Integral Types


The data types byte,short,int, and longare known as integral types (or integer types) because
they refer to integer values—whole numbers with no fractional part. In Java, the simplest form
of integer value is a sequence of one or more digits:


22 16 1 498 0 4600


Commas are not allowed.
A minus sign preceding an integer value makes the integer negative:


–378 –912


The data types byte,short,int, and longare intended to represent different sizes of in-
tegers, from smaller (fewer bits) to larger (more bits), as shown in Figure 3.4.
The Java language specifies the sizes of the integral types to match those shown in the
figure. The more bits in the type, the larger the integer value that can be stored.

Free download pdf