Programming and Problem Solving with Java

(やまだぃちぅ) #1
Java data types

primitive

integral floating point boolean array interface class

byte char short int long float double

reference

(^100) | Arithmetic Expressions
Figure 3.1 Java data types


3.1 Overview of Java Data Types


In Chapter 2, we informally discussed the distinctions among Java’s data types. Now it is time
to make this intuitive understanding formal. Java’s built-in data types are organized into
primitive types and reference types (see Figure 3.1).
You might have noticed that Stringisn’t listed in Figure 3.1. In Chapter 2, we noted that
Stringis an example of a classconstruct, which falls under the category of reference types.
We also used classes such as BufferedReader,InputStreamReader, and System. Recall that our
naming convention is to capitalize the first letter of all classes in this manner, so as to help
us identify them in our code.
The division of Java’s data types intoprimitiveandreferencetypes stems from the way that
Java stores values of each type in memory. We briefly discussed the distinction between these
types in Chapter 2, and now we are ready to take a deeper look at them. Recall that Java stores
each primitive value at the memory address it chooses for it. When we assign a value to a vari-
able of a primitive type, Java copies the value into the address that has been chosen for the vari-
able.This procedure is possible because each primitive type takes a specified amount of space.
Because reference types can contain different numbers of fields and methods, they con-
sume different amounts of the computer’s memory. Most are too large to fit into a single mem-
ory location, so Java stores theaddressof the memory location where the object can be found.
That is, the chosen location contains a binary number that tells the computer where the ob-
ject is stored. When Java assigns an object to a variable, it copies this address into the variable.
Let’s look at a pair of examples that demonstrate the difference between primitive val-
ues and reference values.

charletter;
String title;
String bookName;

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf