Download Computer Science: Problem Solving and Abstraction - Lecture Slides | CMPU 101 and more Study notes Computer Science in PDF only on Docsity!
Chapter 7—Objects and Memory
The Art and Science of
An Introduction
to Computer Science ERIC S. ROBERTS
Java
Objects and Memory
C H A P T E R 7
Yea, from the table of my memory
I’ll wipe away all trivial fond records.
—William Shakespeare, Hamlet, c. 1600
CMPU-
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
The Structure of Memory
• The fundamental unit of memory inside a computer is called a
bit , which is a contraction of the words binary digit. A bit
can be in either of two states, usually denoted as 0 and 1.
• Numbers are stored in still larger units that consist of multiple
bytes. The unit that represents the most common integer size
on a particular hardware is called a word. Because machines
have different architectures, the number of bytes in a word
may vary from machine to machine.
0 0 1 0 1 0 1 0
• The hardware structure of a computer combines individual
bits into larger units. In most modern architectures, the
smallest unit on which the hardware operates is a sequence of
eight consecutive bits called a byte. The following diagram
shows a byte containing a combination of 0s and 1s:
Binary Notation
The rightmost digit
is the units place.
The next digit gives
the number of 2s.
The next digit gives
the number of 4s.
And so on...
• Bytes and words can be used to represent integers of different
sizes by interpreting the bits as a number in binary notation.
0
x 1 = 0
1
x 2 = 2
0 x 4 = 0
42
1 x 8 = 8
0
x 16 = 0
1
x 32 = 32
0 x 64 = 0
0
x 128 = 0
• Binary notation is similar to decimal notation but uses a
different base. Decimal numbers use 10 as their base, which
means that each digit counts for ten times as much as the digit
to its right. Binary notation uses base 2, which means that
each position counts for twice as much, as follows:
0 0 1 0 1 0 1 0
Numbers and Bases
• The calculation at the end of the preceding slide makes it
clear that the binary representation 00101010 is equivalent to
the number 42. When it is important to distinguish the base,
the text uses a small subscript, like this:
2
10
• Although it is useful to be able to convert a number from one
base to another, it is important to remember that the number
remains the same. What changes is how you write it down.
• The number 42 is what you get if you count
how many stars are in the pattern at the right.
The number is the same whether you write it
in English as forty-two, in decimal as 42, or
in binary as 00101010.
• Numbers do not have bases; representations do.
Octal and Hexadecimal Notation
• Because binary notation tends to get rather long, computer
scientists often prefer octal (base 8) or hexadecimal (base
16) notation instead. Octal notation uses eight digits: 0 to 7.
Hexadecimal notation uses sixteen digits: 0 to 9, followed by
the letters A through F to indicate the values 10 to 15.
• The following diagrams show how the number forty-two
appears in both octal and hexadecimal notation:
2
x = 2
1
5 x 8 = 40
5 2
42
10
x = 10
1
02 x 16 = 32
2 A
42
octal hexadecimal
• The advantage of using either octal or hexadecimal notation is
that doing so makes it easy to translate the number back to
individual bits because you can convert each digit separately.
Exercises: Number Bases
• What is the decimal value for each of the following numbers?
2
8
AD
16
1 x 1 = 1
0
x 2 = 0
0
x 4 = 0
0 x 8 = 0
1
x 16 = 1
1 0 0 0 1
17
7 x 1 = 7
7
x 8 = 56
7 7
127
1
1
x 64 = 64
13 x 1 = 13
10
x 16 = 160
A D
173
• As part of a code to identify the file type, every Java class file
begins with the following sixteen bits:
1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 0
How would you express that number in hexadecimal notation?
1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 0
A F E
CAFE
16
1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 0
Memory and Addresses
• Every byte inside the primary memory of a machine
is identified by a numeric address. The addresses
begin at 0 and extend up to the number of bytes in
the machine, as shown in the diagram on the right.
• In these slides as well as in the diagrams in the text,
memory addresses appear as four-digit hexadecimal
numbers, which makes addresses easy to recognize.
• In Java, it is impossible to determine the address of
an object. Memory addresses used in the examples
are therefore chosen completely arbitrarily.
• Memory diagrams that show individual bytes are
not as useful as those that are organized into words.
The revised diagram on the right now includes four
bytes in each of the memory cells, which means that
the address numbers increase by four each time.
000A
000B
FFF
FFF
FFF
FFF
FFF
FFF
FFFA
FFFB
FFFC
FFFD
FFFE
FFFF
000C
001C
002C
FFD
FFD
FFD
FFDC
FFE
FFE
FFE
FFEC
FFF
FFF
FFF
FFFC
The Allocation of Memory to Variables
• When you declare a variable in a program, Java allocates
space for that variable from one of several memory regions.
• One region of memory is reserved for variables that
are never created or destroyed as the program runs,
such as named constants and other class variables.
This information is called static data.
static
data
stack
FFFF
• Each time you call a method, Java allocates a new
block of memory called a stack frame to hold its
local variables. These stack frames come from a
region of memory called the stack.
• Whenever you create a new object, Java allocates
space from a pool of memory called the heap.
heap
• In classical architectures, the stack and heap grow
toward each other to maximize the available space.
Heap-Stack Diagrams
• It is easier to understand how Java works if you have a good
mental model of its use of memory. The text illustrates this
model using heap-stack diagrams , which show the heap on
the left and the stack on the right, separated by a dotted line.
• Whenever your program creates a new object, a block of
memory is added to the heap. That block must be large
enough to store the instance variables for the object, along
with some extra overhead space required for any object.
Overhead space is indicated in heap-stack diagrams as a
crosshatched box.
• Whenever your program calls a method, a block of memory is
added to the stack. The local variables for the method are
each given space on the stack with some overhead
information identifying the method. When a method returns,
Java reclaims the memory in its frame.
Object References
• Internally, Java identifies an object by its address in memory.
That address is called a reference.
stack
r
FFFC
• The local variable r1 is allocated in the current stack frame
and is assigned the value 1000 , which identifies the object.
• The next slide traces the execution of the TestRational
program from Chapter 6 using the heap-stack model.
Rational r1 = new Rational(1, 2);
heap
den 2
num 1
it allocates heap space for the new Rational object. For this
example, imagine that the object is created at address 1000.
• As an example, when Java evaluates the following line
A Complete Heap-Stack Trace
skip simulation
a
b
c
sum
FFFC
FFF
FFF
FFF
FFEC
100C
TestRational
stack
This object is a temporary value
used only during the calculation.
public void run() {
Rational a = new Rational(1, 2);
Rational b = new Rational(1, 3);
Rational c = new Rational(1, 6);
Rational sum = a.add(b).add(c);
println(a + " + " + b + " + " + c + " = " + sum);
}
den
num 1
den
num 5
den
num 1
den
num 1
den
num 1
public Rational add(Rational r) {
return new Rational( this.num * r.den + r.num * this.den ,
this.den * r.den );
} 6
5
1 3 1 2
public Rational add(Rational r) {
return new Rational( this.num * r.den + r.num * this.den ,
this.den * r.den );
} 36
36
heap
102C
101C
100C
100C
this
r
FFE
FFE
FFE
100C
This stack frame is created
for the constructor.
This stack frame is created
for the add method.
All objects are created
in the heap.
TestRational
public void run() {
Rational a = new Rational(1, 2);
Rational b = new Rational(1, 3);
Rational c = new Rational(1, 6);
Rational sum = a.add(b).add(c);
println(a + " + " + b + " + " + c + " = " + sum);
}
den
num 1
den
num 5
den
num 1
den
num 1
den
num 1
heap stack
a
b
c
sum
FFFC
FFF
FFF
FFF
FFEC
100C
102C
101C
100C
The Pointer Model
den 1
num
den 6
num
den 6
num
den 3
num
den 2
num
heap stack
a
b
c
sum
FFFC
FFF
FFF
FFF
FFEC
100C
102C
101C
100C
• The heap-stack diagram at the lower left shows the state of
memory at the end of the last slide.
• The diagram at the lower right shows exactly the same state
using arrows instead of numeric addresses. This style of
diagram is said to use the pointer model.
den 1
num 1
den 6
num 5
den 6
num 1
den 3
num 1
den 2
num 1
a
b
c
sum
heap stack
Stack-Heap diagram
value
heap stack
x
FFFC
1000 FFF
caller
Number
• When x is instantiated in this example, the address on the
heap where the Number object named x is stored is written
on the stack and named x in the stack frame for the caller
method.
• When add1 is called, the address in the stack for x is copied
into the stack frame for add1 and named y. Changes made
to parameter y are also made to the argument x because both
the argument and the parameter name refer to the same object
on the heap.
Wrapper Classes
• The designers of Java chose to separate the primitive types
from the standard class hierarchy mostly for efficiency.
Primitive values take less space and allow Java to use more of
the capabilities provided by the hardware.
• Even so, there are times in which the fact that primitive types
are not objects gets in the way. There are many tools in the
Java libraries—several of which you will encounter later in
the book—that work only with objects.
• To get around this problem, Java includes a wrapper class to
correspond to each of the primitive types:
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short
Using Wrapper Classes
• You can create an instance of a wrapper class by calling its
constructor with the primitive value. For example, the line
Integer five = new Integer(5);
heap
creates a new Integer object containing the value 5:
stack
five 1000 FFFC
• The value stored in the variable five is an object, and you
can use it in any contexts that require objects.
• For each of the wrapper classes, Java defines a method to
retrieve the primitive value, as illustrated below:
int underlyingValue = five.intValue();
Boxing and Unboxing
• As of Java Standard Edition 5.0, Java automatically converts
values back and forth between a primitive type and the
corresponding wrapper class. For example, if you write
Integer five = 5;
Java will automatically call the Integer constructor.
• These operations are called boxing and unboxing.
• Similarly, if you then write
int six = five + 1;
Java will automatically call intValue before the addition.
• Although boxing and unboxing can be quite convenient, this
feature can generate confusion and should be used with care.
Exercise: Stack-Heap Diagrams
public TestLinePoint() {
Point p1 = new Point(0, 0);
Point p2 = new Point(200, 200);
Line line = new Line(p1, p2);
}
public class Point {
public Point(int x, int y) {
cx = x;
cy = y;
}
... other methods appear here...
private int cx;
private int cy;
}
Suppose that the classes Point and Line are defined as follows:
public class Line {
public Line(Point p1,
Point p2) {
start = p1;
finish = p2;
}
... other methods appear here...
private Point start;
private Point finish;
}
Draw a heap-stack diagram showing the state of memory just before
the following constructor finishes.
Solution: Stack-Heap Diagrams
finish 100C
start
cy 200
cx
cy 0
cx
heap
stack
p
p
line
FFFC
FFF
FFF
FFF
100C
101C
100C
finish
start
cy 200
cx 200
cy 0
cx 0
p
p
line
heap stack
Address Model Pointer Model
Linking Objects Together
• Although most examples of this technique are beyond the
scope of a first course, references are particularly important in
computer science because they make it possible to represent
the relationship among objects by linking them together in
various ways.
link
data
• One common example is called a linked list , in which each
object in a sequence contains a reference to the one that
follows it:
link
data
link
data
link null
data
• Java marks the end of linked list using the constant null ,
which signifies a reference that does not actually point to an
actual object. The value null has several other uses, as you
will discover in the chapters that follow.
The Beacons of Gondor
Minas Tirith Amon Dîn Eilenach Nardol Erelas Min-Rimmon Calenhad Halifirien Rohan
For answer Gandalf cried aloud to his horse. “On, Shadowfax!
We must hasten. Time is short. See! The beacons of Gondor are
alight, calling for aid. War is kindled. See, there is the fire on
Amon Dîn, and flame on Eilenach; and there they go speeding
west: Nardol, Erelas, Min-Rimmon, Calenhad, and the Halifirien
on the borders of Rohan.”
—J. R. R. Tolkien, The Return of the King, 1955
In a scene that was brilliantly captured in Peter Jackson’s film
adaptation of The Return of the King, Rohan is alerted to the
danger to Gondor by a succession of signal fires moving from
mountain top to mountain top. This scene is a perfect illustration
of the idea of message passing in a linked list.
Message Passing in Linked Structures
public class SignalTower {
/* Constructs a new signal tower */
public SignalTower(String name,
SignalTower link) {
towerName = name;
nextTower = link;
* Signals this tower and passes the
* message along to the next one.
public void signal() {
lightCurrentTower();
if (nextTower != null) {
nextTower.signal();
/* Marks this tower as lit */
public void lightCurrentTower() {
... code to draw a fire on this tower...
/* Private instance variables */
private String towerName;
private SignalTower nextTower;
To represent this message-passing
image, you might use a definition
such as the one shown on the right.
Minas Tirith
Amon Dîn
Eilenach
Nardol
Erelas
Min-Rimmon
Calenhad
Halifirien
Rohan
null
You can then initialize a chain of
SignalTower objects, like this:
Calling signal on the first tower
sends a message down the chain.
The End