Java Reference
In-Depth Information
Q I'm confused about the differences between objects and the primitive data
types, such as
int
and
boolean
.
A
The primitive types (
byte
,
short
,
int
,
long
,
float
,
double
,
boolean
, and
char
)
are not objects, although in many ways they can be handled like objects: They can
be assigned to variables and passed in and out of methods.
Objects are instances of classes and, as such, are usually much more complex data
types than simple numbers and characters, often containing numbers and characters
as instance or class variables.
Q The
length()
and
charAt()
methods in Listing 3.3 don't appear to make
sense. If
length()
says that a string is 36 characters long, shouldn't the char-
acters be numbered from 1 to 36 when
charAt()
is used to display characters
in the string?
A
The two methods look at strings a little differently. The
length()
method counts
the characters in the string, with the first character counting as 1, the second as 2,
and so on. The string
“Charlie Brown”
has 13 characters. The
charAt()
method
considers the first character in the string to be located at position number 0. This is
the same numbering system used with array elements in Java. The string
Charlie
Brown
has characters ranging from position 0 (the letter
“C”
) to position 12 (the let-
ter
“n”
).
Q If Java lacks pointers, how can I do something like linked lists, where there's a
pointer from one node to another so that they can be traversed?
A
It's untrue to say that Java has no pointers at all; it just has no explicit pointers.
Object references are, effectively, pointers. To create something like a linked list,
you could create a class called
Node
, which would have an instance variable also of
type
Node
. To link together node objects, assign a node object to the instance vari-
able of the object immediately before it in the list. Because object references are
pointers, linked lists set up this way behave as you would expect them to. (You'll
work with the Java class library's version of linked lists on Day 8, “Data
Structures.”)
3