Using objects (chapter 3)

Download Report

Transcript Using objects (chapter 3)

Using Objects
Chapter 3
Spring 2005
CS 101
Aaron Bloomfield
1
About the assignment statement
 Assign the value 5 to the variable x
 int x;
 x = 5;
 5 = x;
NOT VALID!
 This is not a mathematical equals
 It’s a Java assignment
 The variable you want to copy the value to MUST be on the
left
 The value you want to copy MUST be on the right
 Assignment copies the value on the right to the variable on
2
the left
Getting classy
 Purpose of this chapter
 Gain experience creating and manipulating objects from
the standard Java types
 Why
 Prepares you for defining your own classes and creating
and manipulating the objects of those classes
3
Values versus objects
 Numbers
 Have values but they do not have behaviors
 Objects
 Have attributes and behaviors
 System.in
 References an InputStream
 Attribute: keyboard
 Behaviors: reading
 System.out
 References an OutputStream
 Attribute: monitor
 Behaviors: printing
4
Java and variables
 Consider:
int x = 7;
double d;
char c = ‘x’;
int x
double d
char c
7
-
‘x’
 The variable name is the actual spot in memory where the
value is stored
5
What is a reference
 A reference is a memory address
 References are like pointers in C/C++
 But they are not the exact same thing!
 C++ has references also (in addition to pointers)
 You may her me call them pointers instead of references
 All objects in Java are declared as references
6
References 1
 Consider:
int j = 5;
String s = “Hello world”;
Note that there is
no “new” here
 Java translates that last line into:
String s = new String (“Hello world”);
(Not really, but close enough for this lecture)
7
References 2

What’s happening in memory
int j = 5;
String s = “Hello world”;
String s
0x0d4fe1a8
Takes up 32 bits
(4 bytes) of memory
Takes up 32 bits
(4 bytes) of memory
int j
5
At memory location
0x0d4fe1a8
Takes up 12
bytes of memory

Hello world
Primitive types are never references; only objects
8
Quick survey

a)
b)
c)
d)
I understand those slides on references…
I think so
I need some more review
Not really
Reference what?
9
An old prediction of the future…
10
Other Java object types
 String
 Rectangle
 Color
 JFrame
11
Representation
 Statements
int peasPerPod = 8;
String message = "Don't look behind the door!“
message
peasPerPod
String
- text = "Don't look behind the door!"
- length = 27
- ...
+ length () : int
+ charAt ( int i ) : char
+ subString ( int m, int n ) : String
+ indexOf ( String s, int m ) : int
+ ...
12
Representation
String s = “I love CS 101”;
int l = s.length();
char c = s.charAt (3);
String t = s.subString(1,2);
int t = s.indexOf (t, 0);
message
String
- text = "Don't look behind the door!"
- length = 27
- ...
+ length () : int
+ charAt ( int i ) : char
+ subString ( int m, int n ) : String
+ indexOf ( String s, int m ) : int
+ ...
13
Shorthand representation
 Statements
int peasPerPod = 8;
String message = "Don't look behind the door!“
peasPerPod
message
8
"Don't look behind the door!"
14
Examples
 Consider
String a = "excellence“;
String b = a;
 What is the representation?
a
"excellence"
b
15
Uninitialized versus null
 Consider
String dayOfWeek;
Scanner inStream;
 What is the representation?
dayOfWeek
-
inStream
-
16
Uninitialized versus null
 Consider
String fontName = null;
Scanner fileStream = null;
 What is the representation?
fontName
null
fileStream
null
OR
fontName
fileStream
17
The null reference
 Sometimes you want a reference to point to nothing
 Use the null reference:
String s = null;
 The null reference is equivalent to a memory address of zero
(0x00000000)
 No user program can exist there
18
The null reference
 Consider:
String s = “Hello world”;
System.out.println (s.length());
 What happens?
 Java prints
out 11
s
String
- text = “Hello world"
- length = 11
- ...
+ length () : int
+ charAt ( int i ) : char
+ subString ( int m, int n ) : String
+ indexOf ( String s, int m ) : int
+ ...
19
The null reference
 Consider:
String s = null;
System.out.println (s.length());
 This is called accessing (or following) a null pointer/reference
 What happens?
 Java: java.lang.NullPointerException
 C/C++: Segmentation fault (core dumped)
 Windows: …
20
What happens in Windows…
21
So what is a null reference good for?
 Let’s say you had a method that returned a String when
passed some parameters
 Normally it returns a valid String
 But what if it can’t? How to deal with that?
 Return a null reference
22
Quick survey

a)
b)
c)
d)
I understand null references…
Pretty much
Once I read the text, I’ll be good
Not really
What’s a reference again?
23
A bit of humor…
24
References and memory
 Most modern computers are 32-bit computers
 This means that a reference takes up 32 bits
 232 = 4 Gb
 This means that a 32-bit machine cannot access more
than 4 Gb of memory!
 Well, without doing some “tricks”, at least
 Most machines come with 1 Gb memory these days
 Will come with 4 Gb in a year or so
 64-bit machines will have a maximum of 16 exabytes of
memory
 Giga, Tera, Peta, Exa
 That’s 16 billion Gb!
25
References 4

Consider:
String s1 = “first string”;
String s2 = “second string”;
s2 = s1;
System.out.println (s2);
What happens
to this?
String s1
“first string”
“second string”
String s2
length = 12
length = 13
26
Java’s garbage collection
 If an object in memory does not have a reference pointing to
it, Java will automagically delete the object
 This is really cool!
 In C/C++, you had to do this by yourself
27
Assignment
 Consider
String word1 = "luminous";
String word2 = "graceful";
Word1 = word2;
Garbage
collection
time!
 Initial representation
word1
"luminous"
word2
"graceful"
28
Using objects
 Consider
Scanner stdin = new Scanner(System.in);
System.out.print("Enter your account name: ");
String response = stdin.next();
 Suppose the user interaction is
Enter your account name: artiste
reponse
stdin
"artiste"
Scanner:
29
String representation
 Consider
 String alphabet = "abcdefghijklmnopqrstuvwxyz";
 Standard shorthand representation
alphabet
"abcdefghijklmnopqrstuvwxyz"
 Truer representation
alphabet
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
y
30
z
String representation
 Consider
 String alphabet = "abcdefghijklmnopqrstuvwxyz";
 char c1 = alphabet.charAt(9);
 char c2 = alphabet.charAt(15);
 char c3 = alphabet.charAt(2);
 What are the values of c1, c2, and c3? Why?
c1
'j'
c2
'p'
c3
'c'
31
Program WordLength.java
public class WordLength {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = stdin.next();
int wordLength = word.length();
System.out.println("Word " + word + " has length "
+ wordLength + ".");
}
}
32
More String methods
 Consider
String weddingDate = "August 21, 1976";
String month = weddingDate.substring(0, 6);
System.out.println("Month is " + month + ".");
 What is the output?
Month is August.
33
More String methods
 Consider
String fruit = "banana";
String searchString = "an";
int n1 = fruit.indexOf(searchString, 0);
int n2 = fruit.indexOf(searchString, n1 + 1);
int n3 = fruit.indexOf(searchString, n2 + 1);
System.out.println("First search: " + n1);
System.out.println("Second search: " + n2);
System.out.println("Third search: " + n3);
 What is the output?
First search: 1
Second search: 3
Third search: -1
34
Quick survey

a)
b)
c)
d)
I understand how one selects methods from an
object.
Absolutely!
Kind of
Not really
What’s an object again?
35
Today’s dose of demotivators
36
Variables vs. Types

The type is the recipe or template for how to create a variable
 Examples: int, double, char, boolean, etc.
 There are only 8 primitive types
 There are only two things you can do with a type:
 Declare a variable
 int x;
 Use it as a cast
 x = (int) 3.5;
 There is only one of each type

The variable is the actual instance of a type in memory
 It’s a spot in memory where you store a value
 You choose the name: width, x, thatThemThereValue, etc.
 You can have as may variables as you want

Like the difference between a recipe and a bunch of cookies
38
Quick survey

a)
b)
c)
d)
I understand the difference between variables
and types
Very well
With some review, I’ll be good
Not really
Not at all
39
Classes vs. Objects
 A class is a user-defined “thing”
 Examples: String, Scanner, Rectangle, etc.
 We’ll start defining our own classes next chapter
 Classes are more complex than the primitive types
 A class is analogous to a type
 It’s just more complex and user-defined
 There can be only one class of each name
 An object is an instance of a class
 There is only one String class, but you can have 100
String objects
 A object is analogous to a variable
 It just is a reference instead
 A class is a “template” used for creating objects
40
More on classes vs. objects
41
Quick survey

a)
b)
c)
d)
I understand the difference between classes
and objects
Very well
With some review, I’ll be good
Not really
Not at all
42
More String methods
 Consider
int v1 = -12;
double v2 = 3.14;
char v3 = 'a';
String s1 = String.valueOf(v1);
String s2 = String.valueOf(v2);
String s3 = String.valueOf(v3);
v1
-12
v2
3.14
v3
‘a’
s1
"-12"
s2
"3.14"
s3
"a"
43
Final variables
 Consider
final String POEM_TITLE = “Appearance of Brown";
final String WARNING = “Weather ball is black";
 What is the representation?
POEM_TITLE
WARNING
"Appearance of Brown"
"Weather ball is black"
The locks indicat e t he memory locat ions holds const ant s
44
Final variables
The reference cannot be
modified once it is established
In general, these attributes can be
modified through member methods
Value
object
type
constant
45
Rectangle
int x = 3;
int y = 4;
The upper-left-hand
int width = 5;
corner of the new Rectangle
int height = 2;
Rectangle r = new Rectangle(x, y, width, height);
x
3
y
4
width
5
height
2
The dimensions of
the new Rectangle
(3, 4)
r
2
Rectangle:
5
46
Final variables
 Consider
final String LANGUAGE = "Java";
The reference cannot be
modified once it is
established
LANGUAGE
"Java"
47
Rectangle
 Consider
final Rectangle BLOCK = new Rectangle(6, 9, 4, 2);
BLOCK.setLocation(1, 4);
BLOCK.resize(8, 3);
(6, 4)
(1,
9)
BLOCK
2
3
Rectangle:
4
8
48
String method usage
x
10
y
4
 Consider:
String s = "Halloween";
String t = "Groundhog Day";
v
String u = "May Day";
String v = s.substring(0,6);
“Hallow"
int x = t.indexOf ("Day", 0);
int y = u.indexOf ("Day");
String
s = t;
- text = “May
“Halloween"
“Groundhog
Day" Day"
u = null;
s
“Halloween"
t
“Groundhog Day"
u
“May Day"
- length = 7
9
13
- ...
+ length () : int
+ subString ( int m, int n ) : String
+ indexOf ( String s, int m ) : int
+ indexOf ( String s ) : int 49
+ ...
String method usage
x
10
y
 Consider:
String s = "Halloween";
String t = "Groundhog Day";
v
final String u = "May Day";
String v = s.substring(0,6);
“Hallow"
int x = t.indexOf ("Day", 0);
int y = u.indexOf ("Day");
s = t;
u = null;
Java error:
s
“Halloween"
t
“Groundhog Day"
u
“May Day"
4
cannot assign a
value to final
variable u
50
Rectangle method usage
Rectangle
 Consider:
- width = 1
7
- height = 2
Rectangle r = new Rectangle();
final Rectangle s = new
Rectangle (1, 2, 3, 4);
s
r.setWidth(5);
r.setHeight(6);
r
s.setWidth (7);
r = new Rectangle (8,9,10,11);
s = new Rectangle (12,13,14,15);
+ setWidth ( int w )
+ setHeight ( int wh )
+ setX ( int x )
+ setY ( int y )
+ ...
Rectangle
- width = 8
- height = 9
- x = 10
- y = 11
-x=3
-y=4
Rectangle
- width = 0
5
- height = 0
6
-x=0
-y=0
+ setWidth ( int w )
+ setHeight ( int wh )
+ setX ( int x )
+ setY ( int y ) 51
+ ...
Scanner review
 To initialize a Scanner object:
 Scanner stdin = new Scanner (System.in);
 Scanner stdin = Scanner.create (System.in);
 This one will not work!
 To read an int from the keyboard:
 stdin.nextInt();
 To read a double from the keyboard:
 stdin.nextDouble();
 To read a String from the keyboard:
 stdin.next();
52
Scanner usage examples
 Consider:
Scanner stdin = new Scanner (System.in);
int x = stdin.nextInt();
double d = stdin.nextDouble();
String s = stdin.next();
stdin
x
s
Scanner:
5
d
3.5
“hello world”
53
Quick survey

a)
b)
c)
d)
I felt I understood the material in this slide set…
Very well
With some review, I’ll be good
Not really
Not at all
54
Quick survey

a)
b)
c)
d)
The pace of the lecture for this slide set was…
Fast
About right
A little slow
Too slow
55
Quick survey

a)
b)
c)
d)
How interesting was the material in this slide
set? Be honest!
Wow! That was SOOOOOOO cool!
Somewhat interesting
Rather boring
Zzzzzzzzzzz
56
A bit of humor…
57