Java Reference
In-Depth Information
Chapter 2 introduced you to the basic elements of Java programs, including special
symbols and identifiers, primitive data types, arithmetic operators, and the order of
precedence of arithmetic operators. You were briefly introduced to the
class
String
for processing strings, the
class
Scanner
for inputting data into a program, and general
rules on programming style. In this chapter, you will learn more about input and output
and how to use predefined methods in your programs. You will also learn, in some detail,
how to use the
class
String
to process strings.
Three terms that you will encounter repeatedly throughout this topic are variables, reference
variables, and objects. We define these terms now so you will be familiar with them.
In Chapter 2, you learned about the primitive data types, such as
int
,
double
,and
char
.
You also worked with strings. We used
String
variables to manipulate or process strings.
Consider the following statement:
int
x;
//Line 1
This statement declares
x
to be an
int
variable. Now consider the statement:
String str;
//Line 2
This statement declares
str
to be a variable of type
String
.
The statement in Line 1 allocates memory space to store an
int
value and calls this
memory space
x
. The variable
x
can store an
int
value in its memory space. For example,
the following statement stores
45
in
x
, as shown in Figure 3-1:
x = 45;
//Line 3
x
45
FIGURE 3-1
Variable
x
and its data
Next, let us see what happens with the statement in Line 2. This statement allocates
memory space for the variable
str
. However, unlike the variable
x
, the variable
str
cannot directly store data in its memory space. The variable
str
stores the memory
location, that is, the address of the memory space where the actual data is stored. For
example, the effect of the statement:
str = "Java Programming";
//Line 4
is shown in Figure 3-2.
Search WWH ::
Custom Search