46
chapter 2
A
B
Code Magnets:
File Edit Window Help Dance
% java DrumKitTestDrive
bang bang ba-bang
ding ding da-ding
class DrumKit {
boolean topHat = true;
boolean snare = true;
void playTopHat() {
System.out.println(“ding ding da-ding”);
}
void playSnare() {
System.out.println(“bang bang ba-bang”);
}
}
class DrumKitTestDrive {
public static void main(String [] args) {
DrumKit d = new DrumKit();
d.playSnare();
d.snare = false;
d.playTopHat();
if (d.snare == true) {
d.playSnare();
}
}
}
class DVDPlayerTestDrive {
public static void main(String [] args) {
DVDPlayer d = new DVDPlayer();
d.canRecord = true;
d.playDVD();
if (d.canRecord == true) {
d.recordDVD();
}
}
The line: d.playDVD( ); wouldn’t
} compile without a method !
%XERCISE3OLUTIONS
1dQ^OU_Q
Be the Compiler:
exercise solutions
you are here4
classes and objects
47
public class EchoTestDrive {
public static void main(String [] args) {
Echo e1 = new Echo();
Echo e2 = new Echo( ); // the correct answer
- or -
Echo e2 = e1; // is the bonus answer!
int x = 0;
while (
x < 4
) {
}
File Edit Window Help Assimilate
%java EchoTestDrive
helloooo
helloooo
helloooo
helloooo
10
I am compiled from a .java file.
My instance variable values can be
different from my buddy’s values.
I behave like a template.
I like to do stuff.
I can have many methods.
I represent ‘state’.
I have behaviors.
I am located in objects.
I live on the heap.
I am used to create object
instances.
My state can change.
I declare methods.
I can change at runtime.
class
object
class
object, method
class, object
instance variable
two
places-as
object
state
(instance variables), and as
local
variables
(variables declared
within
a method).Later, we'll use variables as
arguments
(values sent to a
method by the calling code), and as
return
types
(values sent back to the caller of the method).
You've seen variables declared as simpie
prj
mIUve integer vaIues (type
in
c). You've seen
variables declared assomething more
complex
like a String or an array. But
there's
gotta
be
more
to
life
won't
let you do
something
bizarre
and
dangerous
like stuff a
Giraffe reference
into
a Rabbit
variable-what
happens
when
someone
tries to ask
the
so-called
Rabbitto
hop
()?
And it
won't
let you
put
a
floating
point
number
into
an
A single character? Variables
come
in two flavors:
primitive
and
object
reference.
Primitives hold
fundamental
values (think: simple bit patterns)
including integers, booleans,
and
floating
point
numbers
. Object references hold. well,
references
to
objects
(gee,
didn't
that clear it up.)
We'Ulook
at
primitives first
and
then
move
on
to
chapter
3
Note: When you see a
statement
like: "an object
of type X",
think
of l)'Peand classes synonyms.
(We'll refine that a little
more
in
later
chapters.)
primitives and references
Primitive
Types
Integer
byte 8 bits
-128 to 127
short
16 bits
-32768 to
32767
int
32 bits
-2147483648
to 2147483647
long 64 bits
-huge to huge
Type
= false;
boolean powerOn;
powerOn
= IsFun;
long big
=
3456789j
float f =
32.5i
.(
qatta
"a~t
-that
Nott
tht
~
btU\,<St
ja~a
thi"~
,i-th
a
~\.
~\oab~
foi"t
I~
'"'ythi,,~
'fI1-th
a
\,<St
'~'.
And
inJava, primitives
come
in different sizes,
and
those sizes
have names.
When
you declare a variable in Java,
I
E ::a-YoU
must
declare it with a specific type.
The
four
containers
here
are
for
the
four
integer
primitives inJava.
fang
int
short
byte
cup
holds a value, so
for
please, with
the
value
:H86,
and
name
the
variable
height.
" Each primitive variable has a fixed
ber
of bits
(cup
size).
The
sizes for the six
numeric
primitives inJava
shown below:
n you
think
of
Java variables,
think
of
cups. Coffee cups, tea cups,
giant
that hold lots
and
lots of beer, those big
a little
later
we'll look
at
cups
hold
references
to
objects.
Stay with us
here
on
the
whole
cup
analogy-as
pie as it is
right
now, it'll give us a
common
way to
look
at things
when
discussion gets
more
complex.
And
that'll
happen
counter,
u can
order
appropriately:
you
are
here
~
51
prlmltlve
assignment
You
really
dot1~t
wat1t
to
spill
that
Be
sure
the value
can
fit
into
the
variable.
You
can't
put a large value
pour
an
int-full
of
stuff
into a byte-sized
container, asfollows:
int
x =
24;
byte
b =
x;
//won't
work!!
Why
doesn't
this work, you ask? After all,
the
value
of
x is 24,
and
24 is definitely
small
enough
to fit
into
a byte.
You
what
the
value
of
xis. even
if
you
happen
to
be able
to
see it literally in
your
code.
You
can
assign
a value to a variable in
one
of
several waysincluding:
• type a litera/value after
the
equals sign (x=12. isGood = true,
etc.)
• assign
the
value
of
one
rlables, seeif you
can figure out which of these
are legal and which aren't,
We haven't covered all the
rules
yet, so on some of these
you'll have to use your best
judgment.
Tip: The compiler
always errs on the side
of
safety.
From the following
list
Circle
the statements that would be
legal if these lines were in
a
single method:
1.
int
x =
34.5;
2 .
boolean
boo
x;
3 .
int
g =
n '"
12;
8.
byte
b =
3;
7.
s =
y;
9 .
byte
v =
b;
declare
an
int
named
size,
assIgn
ilthe
value
32
declare
a
char
named
initial,
assign
itlhe
value
assign
Itlhe
value
that
is
the
sum
of
whatever
xis
now
plus
456
true;
isCrazy
char
initial
=
'j';
52
chapter
3
prlmitJves and
references
Jack
away
frotH
that
keyword!
lbu
are
slightly
more
flexible,
t these will
keep
you safe) :
•
It
must
start
with
a
letter,
underscore
U,
or
dollar
algn
($).
You
can't
atart
a
name
with
a
number.
•
After
80
long
as
It
Isn't
one
of
Java's
reserved
words.
. ' ftIfIeS
ote:
b\e
,
/'It
primitIve '7" float do
U
.
Theelg e
s\"lOft
lot
long
. t/'lem:
\
eao char
byt
membermg
boO onicfor re
, om
nem
are
reserved as well:
void
static
public
fhls
table
reserved.
boolean
byte
mar
double
flom
Inl
long
protected
abstract
flnal
native
storic
strictfp
syn
dJronlzed
transient
If
else
do
while
swllm
case
long
floa.t
double
t
there
are
a
lot
more
we haven
't
discussed yet. Even
if
you
don't
ed
to
know
what
they
mean,
you
still
need
to know you
can
't
use
'em yourself. Do
not-under
them
down cold.
Java's keywords and other reserved words (In no useful order). If you use these for names, the complier will be very, vel}' upset.
you
are
here
I
53
object
references
Controlling
your
~og
object
You know how to declare a primitive variable
and
assign
it
a
value .
But
now
what
about
non-primitive variables? In
other
words, what about
objects?
• There Is
actually
really know whatIs Inside a reference variable. We do
know
that
whatever It Is, It represents one and only one
object. And the JVM knows
how
to
use the reference to
get
to
the object.
You can '1 stuffan object
into
a variable. We often
think
of
it
that
way
we say things like, "I passed
the
String to
the
System.out.printlnf)
method."
Or,
"The
method
returns
a Dog",
Although a primitive variable is full
of
bits
representing
the
actual value of
the
variable, an object reference variable is full
of bits
representing
a wayto getto the
obJect.
You use
the
dot
operator
(.)
on
a
reference
variable 10
say,
"use
the
thing
before
the
dot
to
get
control for that object.
54
chapter
3
Dog d =
new
Dog();
d.bark();
\ thi.k
ot
this
Thillk
o-f
a
D~
referente
vdl'iable
al
a
D~
l'en-ote
to.\h-ol.
You.
IUC
it
to
~tt
-t\l~
objut
todo
Dog();
At1
object
referet1ce
is
just
a"other
variable
value.
O
Declare a
reference
variable
Dog
Dog
object
Dog
object
Doq
myDoq =
new
Dog
()
;
Tells the JVM to allocate space for a
reference variable, and names that
variable
myDog. The reference variable
Is,forever. of type Dog
.ln
Dog
myDog
'"
new
Dog
()
;
Tellsthe JVM to allocate space for a
new Dog object on the heap (we'll
learn a
lot
more about that process,
especially in chapter
9,)
~\.\.
J~itive
U
vall.4t
byte
Dog
myDog =
new
Doq()
;
Something
that
goes In a cup.
Only
this
time,
references
D
:the
re
l
~
o
"
ume
~uest19115
Q:How big
15
a reference
variable?
A.
:Vou don't know. Unless
you're cozy with someone on the
JVM's
development team, you
don't know how a reference is
represented.There are pointers
in there somewhere, but you
can't access them.
You
won't
need to.
(OK,
Ifyou Inslst, you
might as wellJust imagine It
to be a 54-bit value.) But when
objects
to which
they
refer?
A.:
Yep.
All
references for a
given NM willbe the same
size regardless of
the
objects
they reference, but each
JVM
might have a different way of
representing references, so
references on one
JVM
may be
smaller or larger than references
on another
JVM.
Q:can Ido
arithmetic
on a
reference variable, Increment
It
you
know
- Cstuff7
can you
refer to a Dog and then
five
minutes later refer to a Car?
Reference: or coursenot- Once I'm declared, that's it.
If
I'm a Dog remote control
then runever be able to point (oops- my bad, we're not supposed to say
poin~
I mean
rifer
to anything but a Dog.
HeadFirst
Does that mean you canrefer to only one Dog?
Reference: No. I canbe referring to one Dog, and then
five
minutes later I canrefer to
some
other
Dog. As long asit's a Dog, I can be redirected
(like
reprogranuning your remote
to a differentTV) to it. Unless no never mind.
HeadFirst
No, tellme.What were you gonna say?
Reference: I don't think you want to get into
this
now,but I'lljust giveyou the short
version-
if
Yes,
but it
disturbs
me
to
talkabout it.
HeadArst
Why is that?
Reference: Becauseit means
I'm
null,
and that's upsetting to me.
HeadFirst
You
mean.
because
then you have no value?
Reference: Oh,
null
isa value. I'm stilla remote control, but it'slikeyou brought
home a new
universal
remote control and you don't have a
TV
I'm
not programmed to
control
anything.
They
can
garbage
collection.
Sniff.
But do you think programmers ever consider
!haP.
Snif.Why,
wIrY
can't I bea primi-
tive? I
hate
being
a
refcrcut.
The
responsibility,all the broken attachments
ott
the
garbage
collectible
heap
=
new
Book();
=
new
Book();
e
two
Book reference
them, and stick
that
copy
Into
d."
c
and
d
refer
to
the
same
ect.
The
c
and
d
variables
hold
two
dlHerent
copies
of
the
me
value.
Two
object.
References:3
Objects: 2
Book
Book
Book
Book
primitives
and
references
you
are
here
~
57
objects
on the heap
Ufe
a.,d
death
0.,
the
heap
Book b = new
Book()
;
Book c
= new
Book()
i
hold
identical values.
Both
band
c
refer
to
the
••
me
object.
Object
1
I.
abandoned
and
eligible
for
Garbage
Collec-
tion
(GC).
Active References:2
Reachable Objects: 1
Abandoned Objects: 1
The first
object
that
b referenced, Object 1,
has no more references. It's
not
eligible
for
GC.
ActIve References: 1
null References: 1
Reachable Objects: 1
Abandoned Objects: 1
68
chapter
3
Book
primitives
and
references
An
array
is
like
a
tray
of
cups
o
Declare an int array verinble. Anarray variable is
a remote control to an
array
object
.
int[]
int variables.
~
.:is
nums
[0]
=
6;
.3'
~
nums[l]
=
19
;
~
~
nums[2]
=
44:
·s
nums[3]
=
42:
nums
[4]
=
10:
nums[5]
=
20;
nums
of
sophisticated
data
structures
uding
maps, trees.
and
sets
Appendix
B).
but
arrays
are
t
when
you
just
want a quick.
red, efficient list
of
things.
,"'5
give you fast
random
ess by
letting
you use an
index
ition to
get
element
of
that
type. So in an array
of
type
int
(int[])
. each
element
can
hold
an int, In a
Dog
array
(Dog[])
each
element
can
hold
a Dog? No.
remember
that
a
reference
variable
just
holds a
reference
(a
Be
sure
to
notice
one
key
thing
in
the
picture
above - the
arm)'
is
an
object,
even
though it's an arrayof
primitives.
Arrays
are
always objects,
whether
they're
declared
to
bold
primitives
or
object
references.
of
objects
Make
att
array
of
Pogs
pets
=
new
D09[7];
pets[D]
=
new
Dog();
pets[l]
=
new
Dog();
A Create a new Dog
array
with
W a length of 7, and assign
it
to
the
previously-declared
Dog
[J
variable
arrayare
just
Dog reference
variables. We
still
need Dogs!
_
~n,~~:'
:~:f
~~~i:/_t
_
~dmake
-ne
ofthe
11
objects?
58
(
.r 3
Java
cares
about
type.
Once
you've
declared
an
array.
you
are in
the
orrat, so
the.yask eochoneto
~ark,
and
th~n
to their
horror discovertheres a cat
lurkmg.)
And
youcan't stick a
double
intoon
int
orr'atl
(spillage.,
remember?).
You
can,however.
put Q
byte
into
on
in
t arraf,
b~QuSe
a
byte
will
Gtf'OY's
d&elored
type.
,
Dog
name
barkO
eatO
chaseCalO
primitives and references
Cot1trol
your
~og
(with
a
referetlce
variable)
Dog
fide
=
new
Dog();
fido.name
=
~FidoN;
We
created
a
Dog
object
fido.bark()
i
Dog
fido
.chaseCat();
What
happetts
ifthe
POQ
is
Itt
a
OOQ
array?
~e
know we
can
access
the
Dog's
Instance variables
and
methods
using
the
dot
operator,
but
em
what1
new
Dog[3];
myDogs[O]
=
new
Dog()
;
myDogs[O].name
=
"Fido";
myDogs[O]
.bark();
'Yes
we
know
we're
not
demonslralin
-
trying
to
keep
it
simple
.
For
nowW
'1Igdencapsu
iatiOn
he
d ac
cess
it
Dog
dogl
= new
Dog();
dogl.bark{)
;
dogl.name
=
"Bart"
;
A
Pog
exatMple
Dog
name
barkO
eatO
chaseCal()
II now make a Dog
ar
ra
y
Dog() myDogs
= new
Dog[3);
Output
II and
and
reference.
•
Variables
must
always
be
declared
with
a
name
and
a
type.
• A
primitive
variable
value
is
the
b
its
representing
the
value
(5
, 'a',
true,
3.1416,
etc
operator
(.)
on
a
reference
variable
is
like
press
ing
a
button
on
the
remo
le
control
to
access
a
method
or
instance
variable.
• A
reference
variable
has
a
value
as
a
primitive
array
,
only
an
array
that
holds
primitives
.
"Fred" ;
"Marge
" ;
new Dog () ;
new Dog () ;
dog!;
myD
o
gs[O
)
myDog
s[l
)
myDogs [2 )
myDogs(O).name
myDogs(l).narne
II now
100
in
t l n (myDogs
(2)
. narne ) ;
i
nt
x =
0;
whi1e(x
<
mYDOgs
.1ength)~
J
myDogs
[xl
.ba
r k () ; a
\/aYiab\c
l'~~
x = X +
1;
ay-yii'(S
ha\/C
t."c
l'I~bCl"
t)lat.
~\\/ts
'lOlA
a'J
L'
and
detel"llline
whether
each
of
these
files
will
compile.
If
they
won't
cmqpile,
how
would
rOll
fIX
them?
A
B
c
lass
Books
{
String
title;
String
author;
class
Hobbits {
x :: 0;
myBooks{Oj.title :: "The Grapes of Java";
myBooks(lj.title
=
~The
Java Gatsby"i
myBooks(2).title
::
~The
Java Cookbook";
myBooksIO).author
= "bob";
myBooksllj.author::
"sue";
myBooks(2).author
=
"ian";
wbile (x < 3) {
System.ou
t.print(myBookslxj.title)i
System.out.print("
by U)i
System.out.println(rnyBooks[xj.au
thor)
;
x = x + 1;
while (z <
4)
{
z = z + 1;
exercise:
Code
Magnets
Code
Magnets
Aworking
Java
program
Isall scrambled up
on
the
fridge. Can you reconstruct
the
code
snippets to make a working Java program
that
produces
the
output
listed below?
Some of
the
curly braces fell on
the
floor
and
they were too small to pick up, so feel
free to add as many of
those
as you need!
int
[1
index
""
y y +
1;
new
int[4Ji
class
TestArrays
{
public
static
void
main(Strin
N
":J rJ
args)
{
64
chapter
3
primitives and references
_______
.height
(x
+ 1) *
2:
_______
.leogth
that
will compile and
run and produce the
output
listed.
Output
System.out.print(
"triangle
"+x+"
I
area"};
System.out.println("
= " +
.area):
}
x =
27:
Triangle
tS
=
ta[2]:
ta[2J.area
=
343:
System.out.print(uy
=U +
y):
System.out.println(",
tS
area
oncel
you are
her
e
~
65
puzzle: Heap o' Trouble
A
Heap
0'
Trouble
A short Java program is listed to the
right. When
'/1 do stuff' is reached, some
objects and some reference variables
will have been created. Your task Is
to determine
which of the reference
variables refer to which objects. Not all
th e reference variables will be used,and
some objects
might
be referred to more
than once. Draw lines connecting the
reference variables
with
their
matching
objects.
Tip: Unless you're way smarter than us,
while
( x < 3 1 (
hq[x)
=
new
HeapQuiz();
hq(x]
.
id
==
Xi
x = X +
1i
}
hq[3]
==
hq[l]i
hq[4]
hq[l]
;
hq[3]
=
null;
hq
(4)
hq
(0]
;
hq(Ol
==
andstormynight Tawnystrolledintotheprogrammers' bullpenlikeshe
ownedtheplace. Sheknew that all theprogrammerswould still
behardat work,and she
wanted help. She
needed a new methodadded to thepivotalclassthatwas to be loaded into the
client's new top-secretJava-enabledcell phone. Heap
space
in the cellphone's memorywas
as tightas Tawny's top, and everyone knew
it
The normallyraucous buzz inthe bullpenfellto
silenceasTawny
eased
herway to the whiteboard. She sketched a quickoverviewof the new
method's functionality andslowlyscanned
the
room.
'Well
boys, it's cnmch time", she
purred.
'Whoever createsthe mostmemoryefficientversion
of
this methodiscomingwithme to the
client's launch
party on Mauitomorrow to help me install the new software."
The next morningTawnyglidedinto thebullpenwearinghershortAloha dress.
"Gentlemen", she smiled,"the plane leavesin a
fewhours,showme what you've
got!". Bob went
first; as he beganto sketch
updating
stuff
with
ca
"Tawnyrknowwe're tight on memory,but your
spec
saidthat we hadto beable to
access
individualcontactinformationfor allten allowablecontacts,thiswas the best scheme I could
cookup", said Bob. Kentwas next, alreadyimagining coconut
cocktails
with
Tawny,
"Bob,"
he said,
"yoursolution's a bitkludgydon't you think?" Kent smirked,"Takea lookat this
baby":
Contact.
refc;
while
( x < 10 ) {
II
make 10
contact.
objects
refe
= new
Cont.act()i
x = x + 1;
I
class
Books
{
String
title;
String
autbor;
)
if(z==2){
b[z].name = "sam";
}
System.out.print(hlz).name + "
is
a
H);
system.out.println{"good 80bbit
nameH)j
class
Hobbits {
String
name:
public
static
void main{String I) args) {
Hobbits () h
=
ne_w= H :.ob:: :b7i: :t :.s~(3: :)~:
~, , ,
Int
:z
new
Books(3);
int
x =0:
myBooks[O]
:: ntw
9ooksO
;
IUrnanber:
We
hGvt
to
myBooks[1]
:: ntw
BooksO:
actuclily
InQJc.e
the
BooI<s
myBooks[2]
::
new
BooksO:
objects I
~~ =-
l
myBooksIO].title =
uThe
Grapes of
Java';
()
args)
{
int
[)
index
=
new
int{4]:
index[O)
I:
Lndex]
1)
3:
index[
2)
0:
index(3)
2;
String
(]
islands
=
new
String[4]:
islandslO]
"Bermuda":
islandsjl]
=
"Fiji";
primitives
and
references
The
case
of
the
pilfered
references
4.0
10
.0
19
.0
28.0
Tawny
could
see
that
Kent's
method
had
a serious
flaw. It's
true
that
he
didn't
use as many
reference
reference
variable, so
the
previously
referenced
object was
abandoned
on
the
heap
-
unreachable.
Without
access to
nine
of
the
ten
objects
created,
Kent's
method
wasuseless.
(The
software
was
8
huge
success
atKl
Triangle
double
area;
int
height;
int
length,
public
static
void
main(String
[1
argB)
{
lnt
x =0:
Triangle [ ] tel =
new
Trlangle[4];
while
( x • 4 ) {
tel[x] =new Tr/ClllglcQ;
~x].he19ht
~
(x +
1)
*
2;
talx].
length
tS
area
"
U+
tS.area);
}
void
setArea()
{
~
=
(height·
length)
J
2;
~
;,
java
Triangle
triangle
0,
area
triangle
1.
area
criangle
2 ,
area
triangle
3,
behavior,
represented by Instance
variables
and
methods.
But until now, we
haven't looked at how state and behavior are
related.We already know that each instance
of
a
class(each object
of
a particular type) can have its own unique values for its instance variables.
Dog A can have a name "Fido" and a weight of 70 pounds. Dog B Is"Killer"and weighs 9 pounds.
And If the Dog class hasa method makeNoiseO,well,
don't
you
think
a 70-pound dog barks a
bit
deeper than the little 9-pounder7 (Assuming that annoying
ylppy
sound can be considered
a
bark.) Fortunately, that's the whole
point
of an
object-It
has behavior that acts on its state. In
other
does
Song
83
.play
() ;
does
kt10ws
I
C-illi~
playO
0l'I this
iflSta~te
will
t4lASe
"My
W;Y::
to
play.
(blAt
PI~
the
~r.ab-a
~d
Song
title
artist
setTItleO
setArtlstO
playO
lt1stat1ce
different
instance
variable
values. But what
about
the
methods?
}
Song
t2
= new
Song();
t2.setArtist("Travis");
Ca"
every
object
of
that
type
have
dlfferettt
lMethod
behavior?
Well sort
cif.*
Every instance
of
a
particular
class has
represented
by
the
value
of
the
title
instance
variable for
that
instance. So,
if
you call
the
playO
method
on
one
instance you'll
hear
the
song
"Politik", while
another
instance
plays "Darkstar",
The
method
code, however, is
the