using objects
DESCRIPTION
Using Objects. Chapter 3 Fall 2006 CS 101 Aaron Bloomfield. 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. - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/1.jpg)
1
Using Objects
Chapter 3Fall 2006CS 101Aaron Bloomfield
![Page 2: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/2.jpg)
2
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
![Page 3: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/3.jpg)
3
Values versus objects Numbers
Have values but they do not have behaviors In particular, each has only ONE value (or attribute)
Objects Have attributes and behaviors An object can have multiple values (or attributes)
![Page 4: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/4.jpg)
4
Using objects First, we create an object:
Scanner stdin = new Scanner (System.in);
Most object creation lines look like this
Then we use the object stdin.nextInt(); stdin.nextDouble();
Note that we could have called the object foo, bar, or anything stdin is just what we chose to call it
![Page 5: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/5.jpg)
5
Using Rectangle objects Let’s create some Rectangle objects
Rectangle creation: Rectangle r = new Rectangle (10, 20);
Objects have attributes (or properties): System.out.println (r.width); System.out.println (r.height);
Objects have behaviors (or methods): r.grow (10, 20); r.isEmpty(); r.setLocation (5,4);
![Page 6: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/6.jpg)
6
Using String objects Let’s create some String objects
String creation: String s = new String (“Hello world”);
Objects have attributes (or properties): But we can’t access them…
Objects have behaviors (or methods): s.substring(0,6); s.indexOf (“world”); s.toLowerCase();
![Page 7: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/7.jpg)
7
The lowdown on objects Objects are “things” that have properties (attributes) and
behaviors (methods)
We first create one or more objects
We then manipulate their properties and call their methods
![Page 8: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/8.jpg)
8
So why bother with objects? Let’s say you want to do a lot of String manipulation
Once you create a String object, all the manipulation methods are contained therein Sun already wrote the methods for us
So we can use String objects instead of writing our own code to get the substring, indexOf, etc.
![Page 9: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/9.jpg)
9
More on Strings Strings are used very often
As a shortcut, you can use: String s = “Hello world”;instead of: String s = new String (“Hello world”);
It’s just a shortcut that Java allows
The two lines are almost the same There is a minor difference between the two
Which we’ll get to later
![Page 10: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/10.jpg)
10
Visualizing objects
Class (type) name
Attributes (properties)
Methods (behaviors)+ grow (int, int) : void+ isEmpty ( ) : void
+ setLocation ( int, int ) : void+ resize ( int, int ) : void
+ ...
Rectangle
- width = 10- height = 20- ...
![Page 11: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/11.jpg)
11
How well do we understand How well do we understand using objects?using objects?
![Page 12: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/12.jpg)
1212
For Valentine’s Day…For Valentine’s Day…
![Page 13: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/13.jpg)
1313
Bittersweets: Dejected Bittersweets: Dejected sayingssayings
I MISS MY EXI MISS MY EX PEAKED AT 17PEAKED AT 17 MAIL ORDERMAIL ORDER TABLE FOR 1TABLE FOR 1 I CRY ON QI CRY ON Q U C MY BLOG?U C MY BLOG? REJECT PILEREJECT PILE PILLOW HUGGINPILLOW HUGGIN
ASYLUM BOUNDASYLUM BOUND DIGNITY FREEDIGNITY FREE PROG FANPROG FAN STATIC CLINGSTATIC CLING WE HAD PLANSWE HAD PLANS XANADU 2NITEXANADU 2NITE SETTLE 4LESSSETTLE 4LESS NOT AGAIN NOT AGAIN
![Page 14: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/14.jpg)
1414
Bittersweets: Dysfunctional Bittersweets: Dysfunctional sayingssayings
RUMORS TRUERUMORS TRUE PRENUP OKAY?PRENUP OKAY? HE CAN LISTENHE CAN LISTEN GAME ON TVGAME ON TV CALL A 900#CALL A 900# P.S. I LUV MEP.S. I LUV ME DO MY DISHESDO MY DISHES UWATCH CMT UWATCH CMT
PAROLE IS UP!PAROLE IS UP! BE MY YOKOBE MY YOKO U+ME=GRIEFU+ME=GRIEF I WANT HALFI WANT HALF RETURN 2 PITRETURN 2 PIT NOT MY MOMMYNOT MY MOMMY BE MY PRISONBE MY PRISON C THAT DOOR? C THAT DOOR?
![Page 15: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/15.jpg)
15
Review Variables of primitive types
int, double, char, boolean, etc. Can assign a value to it Can read a value from it Can’t do much else!
Objects String, Rectangle, etc. Have many parts
Rectangle has width, length, etc. Like a complex type Have methods
String has length(), substring(), etc.
![Page 16: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/16.jpg)
16
String methods
length(): returns the String’s length (duh!)
String s = “hello world”;String t = “goodbye”;System.out.println (s.length());System.out.println (t.length());
Prints 11 and 7
Note that calling s.length() is different than calling t.length()! Both return the length But of different Strings
![Page 17: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/17.jpg)
17
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.
![Page 18: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/18.jpg)
18
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: 1Second search: 3Third search: -1
![Page 19: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/19.jpg)
2020
String program examplesString program examples
![Page 20: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/20.jpg)
21
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 + ".");}
}
![Page 21: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/21.jpg)
2222
Program demoProgram demo
WordLength.javaWordLength.java
![Page 22: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/22.jpg)
23
More String methods
trim() Returns the String without leading and trailing whitespace Whitespace is a space, tab, or return
![Page 23: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/23.jpg)
24
Date translation Goal: to translate the date from American format to standard
format
![Page 24: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/24.jpg)
25
DateTranslation.java// Convert user-specified date from American to standard format
import java.util.*;
class DateTranslation {
// main(): application entry point static public void main(String args[]) {
// produce a legend (Step 1) // prompt the user for a date in American format (Step 2)
// acquire the input entered by the user (Step 3) // echo the input back (Step 4) // get month entered by the user (Step 5) // get day entered by the user (Step 6) // get year entered by the user (Step 7) // create standard format version of input (Step 8) // display the translation (Step 9)
}}
![Page 25: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/25.jpg)
2626
Program demoProgram demo
DateTranslation.javaDateTranslation.java
![Page 26: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/26.jpg)
2727
Today’s demotivatorsToday’s demotivators
![Page 27: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/27.jpg)
2828
Classes vs. ObjectsClasses vs. Objects
![Page 28: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/28.jpg)
29
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 a few 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 – but only one type!
Like the difference between a recipe and a bunch of cookies
![Page 29: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/29.jpg)
30
How well do we understand How well do we understand variables versus types?variables versus types?
![Page 30: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/30.jpg)
31
Classes vs. Objects A class is a user-defined “thing”
Examples: String, Scanner, Rectangle, etc. We’ll start defining our own classes later this semester
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
![Page 31: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/31.jpg)
32
More on classes vs. objects
![Page 32: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/32.jpg)
33
How well do we understand How well do we understand classes versus objects?classes versus objects?
![Page 33: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/33.jpg)
3434
Lots of piercings…Lots of piercings…
This may be a bit disturbing…This may be a bit disturbing…
![Page 34: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/34.jpg)
3535
ReferencesReferences
![Page 35: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/35.jpg)
36
Java and variables Consider:
int x = 7;double d;char c = ‘x’;
The variable name is the actual spot in memory where the value is stored
Note that d does not have a value
7
int x
-
double d
‘x’
char c
![Page 36: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/36.jpg)
37
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 hear me call them pointers instead of references
All objects in Java are declared as references
![Page 37: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/37.jpg)
38
References 1 Consider:
int j = 5;String s = “Hello world”;
Java translates that last line into:String s = new String (“Hello world”);
(Not really, but close enough for now)
Note that there is no “new” here
![Page 38: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/38.jpg)
39
0x0d4fe1a8
What’s happening in memoryint j = 5;String s = “Hello world”;
Primitive types are never references; only objects
References 2
5
int j
Hello world
String s
Takes up 32 bits(4 bytes) of memory Takes up 32 bits
(4 bytes) of memory
Takes up 12 bytes of memory
At memory location 0x0d4fe1a8
int j = 5;String s = “Hello world”;
![Page 39: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/39.jpg)
40
Representation
message
+ length () : int + charAt ( int i ) : char
+ subString ( int m, int n ) : String+ indexOf ( String s, int m ) : int
+ ...
String
- text = "Don't look behind the door!"- length = 27- ...
Statementsint peasPerPod = 8;String message = "Don't look behind the door!“
peasPerPod 8
![Page 40: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/40.jpg)
41
Representation
s
+ length () : int + charAt ( int i ) : char
+ subString ( int m, int n ) : String+ indexOf ( String s, int m ) : int
+ ...
String
- text = “I love CS 101"- length = 13- ...
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);
A period means “follow the reference”
![Page 41: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/41.jpg)
42
Shorthand represntation Consider:
String s = “Hello world”;
Takes up a lot of space on my slides…
So we’ll use a shorthand representation:
s
+ length () : int + charAt ( int i ) : char
+ subString ( int m, int n ) : String+ indexOf ( String s, int m ) : int
+ ...
String
- text = “Hello world"- length = 11- ...
“Hello world" s
![Page 42: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/42.jpg)
43
Examples Consider
String a = "excellence“;String b = a;
What is the representation?
"excellence"a
b
![Page 43: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/43.jpg)
45
Consider:String s1 = “first string”;String s2 = “second string”;s2 = s1;System.out.println (s2);
“first string”
References 3
String s1
String s2
“second string”
What happensto this?
String s1 = “first string”;String s2 = “second string”;s2 = s1;System.out.println (s2);
![Page 44: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/44.jpg)
46
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
![Page 45: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/45.jpg)
4747
An optical illusionAn optical illusion
![Page 46: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/46.jpg)
4848
The null referenceThe null reference
![Page 47: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/47.jpg)
49
Uninitialized versus null Consider
String dayOfWeek;Scanner inStream;
What is the representation?
-dayOfWeek
-inStream
![Page 48: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/48.jpg)
50
Uninitialized versus null Consider
String fontName = null;Scanner fileStream = null;
What is the representation?
nullfontName
nullfileStream
fontName
fileStreamOR
![Page 49: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/49.jpg)
51
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
![Page 50: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/50.jpg)
52
The null reference Consider:
String s = “Hello world”;System.out.println (s.length());
What happens?
Java prints out 11
s
+ length () : int + charAt ( int i ) : char
+ subString ( int m, int n ) : String+ indexOf ( String s, int m ) : int
+ ...
String
- text = “Hello world"- length = 11- ...
![Page 51: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/51.jpg)
53
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: …
![Page 52: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/52.jpg)
5454
What happens in Windows…What happens in Windows…
![Page 53: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/53.jpg)
55
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
![Page 54: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/54.jpg)
56
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!
![Page 55: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/55.jpg)
5757
MedicineMedicine PhysicsPhysics Public HealthPublic Health
ChemistryChemistry EngineeringEngineering LiteratureLiterature PsychologyPsychology
EconomicsEconomics PeacePeace
BiologyBiology
The 2004 Ig Nobel PrizesThe 2004 Ig Nobel Prizes
"The Effect of Country Music on Suicide.“"The Effect of Country Music on Suicide.“
For explaining the dynamics of hula-hoopingFor explaining the dynamics of hula-hooping
Investigating the scientific validity of the Investigating the scientific validity of the Five-Second RuleFive-Second Rule
The Coca-Cola Company of Great BritainThe Coca-Cola Company of Great Britain
For the patent of the comboverFor the patent of the combover
The American Nudist Research LibraryThe American Nudist Research Library
It’s easy to overlook things – even a man in a It’s easy to overlook things – even a man in a gorilla suit.gorilla suit.
The Vatican, for outsourcing prayers to IndiaThe Vatican, for outsourcing prayers to India
The invention of karaoke, thereby providing The invention of karaoke, thereby providing an entirely new way for people to learn to an entirely new way for people to learn to tolerate each othertolerate each other
For showing that herrings apparently For showing that herrings apparently communicate by fartingcommunicate by farting
![Page 56: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/56.jpg)
5858
Using object examplesUsing object examples
![Page 57: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/57.jpg)
59
Assignment Consider
String word1 = "luminous";String word2 = "graceful";word1 = word2;
Initial representation
Garbage collection
time!
"luminous"word1
"graceful"word2
![Page 58: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/58.jpg)
60
Using objects Consider
Scanner stdin = new Scanner(System.in);System.out.print("Enter your account name: ");String response = stdin.next();
Suppose the user interaction isEnter your account name: artiste
Scanner:stdin
"artiste"reponse
![Page 59: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/59.jpg)
61
String representation Consider
String alphabet = "abcdefghijklmnopqrstuvwxyz";
Standard shorthand representation
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 z
"abcdefghijklmnopqrstuvwxyz"alphabet
![Page 60: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/60.jpg)
62
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?
'j'c1
'p'c2
'c'c3
"abcdefghijklmnopqrstuvwxyz"alphabet
![Page 61: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/61.jpg)
63
Considerint v1 = -12;double v2 = 3.14;char v3 = 'a';String s1 = String.valueOf(v1);String s2 = String.valueOf(v2);String s3 = String.valueOf(v3);
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);
More String methods
"-12"s1
"3.14"s2
"a"s3
v1 -12
v2 3.14
v3 ‘a’
![Page 62: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/62.jpg)
64
Final variables Consider
final String POEM_TITLE = “Appearance of Brown";final String WARNING = “Weather ball is black";
What is the representation?
"Appearance of Brown"POEM_TITLE
"Weather ball is black"WARNING
The locks indicate the memory locations holds constants
![Page 63: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/63.jpg)
65
Final variables Consider
final String LANGUAGE = "Java";
The reference cannot bemodified once it is
established
"Java"LANGUAGE
![Page 64: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/64.jpg)
6666
Today’s demotivatorsToday’s demotivators
![Page 65: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/65.jpg)
67
Rectangle
3x
4y
Rectangle:
5width
height 2
r
5
2(3, 4)
The dimensions ofthe new Rectangle
The upper-left-handcorner of the new Rectangle
int x = 3;int y = 4;int width = 5;int height = 2;Rectangle r = new Rectangle(x, y, width, height);
![Page 66: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/66.jpg)
68
Considerfinal Rectangle BLOCK = new Rectangle(6, 9, 4,
2);BLOCK.setLocation(1, 4);BLOCK.resize(8, 3);
final Rectangle BLOCK = new Rectangle(6, 9, 4, 2);
BLOCK.setLocation(1, 4);BLOCK.resize(8, 3);
Rectangle
Rectangle:BLOCK
4
2(6, 9)
Rectangle:BLOCK
8
3(1, 4)
![Page 67: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/67.jpg)
69
s
t
u
Consider:String s = "Halloween";String t = "Groundhog Day";String u = "May Day";String v = s.substring(0,6);int x = t.indexOf ("Day", 0);int y = u.indexOf ("Day");s = t;u = null;
+ length () : int + subString ( int m, int n ) : String+ indexOf ( String s, int m ) : int+ indexOf ( String s ) : int
+ ...
String
- ...
String method usage
String s = "Halloween";String t = "Groundhog Day";String u = "May Day";String v = s.substring(0,6);int x = t.indexOf ("Day", 0);int y = u.indexOf ("Day");s = t;u = null;
“Groundhog Day"
“May Day"
- text = “Halloween"- length = 9
“Halloween"
- text = “Groundhog Day"- length = 13- text = “May Day"- length = 7
x 10 y 4
“Hallow"
v
![Page 68: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/68.jpg)
70
s
t
u
Consider:String s = "Halloween";String t = "Groundhog Day";final String u = "May Day";String v = s.substring(0,6);int x = t.indexOf ("Day", 0);int y = u.indexOf ("Day");s = t;u = null;
String method usage
“Groundhog Day"
“May Day"
“Halloween"
x 10 y 4
“Hallow"
v
s = t;u = null; Java error:Java error:
cannot assign a cannot assign a value to final value to final
variable uvariable u
![Page 69: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/69.jpg)
71
Consider:
Rectangle r = new Rectangle();final Rectangle s = new
Rectangle (3, 4, 1, 2);r.setWidth(5);r.setHeight(6);s.setWidth (7);r = new Rectangle (10,11,8,9);s = new Rectangle (12,13,14,15);
Rectangle r = new Rectangle();final Rectangle s = new
Rectangle (3, 4, 1, 2);r.setWidth(5);r.setHeight(6);s.setWidth (7);r = new Rectangle (10,11,8,9);s = new Rectangle (12,13,14,15);
s
Rectangle method usage
r
+ setWidth ( int w )+ setHeight ( int wh )+ setX ( int x )+ setY ( int y )+ ...
Rectangle
+ setWidth ( int w )+ setHeight ( int wh )+ setX ( int x )+ setY ( int y )+ ...
Rectangle
- width = 7- height = 2
- x = 3- y = 4
+ setWidth ( int w )
Rectangle
- width = 8- height = 9
- x = 10- y = 11
- width = 1- height = 2
- x = 3- y = 4
- width = 0- height = 0
- x = 0- y = 0
- width = 5- height = 0
- x = 0- y = 0
- width = 5- height = 6
- x = 0- y = 0
![Page 70: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/70.jpg)
72
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();
![Page 71: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/71.jpg)
73
Scanner usage examples Consider:
Scanner stdin = new Scanner (System.in);int x = stdin.nextInt();double d = stdin.nextDouble();String s = stdin.next();
Scanner:stdin
“hello world”s
d 3.5x 5
Scanner stdin = new Scanner (System.in);int x = stdin.nextInt();double d = stdin.nextDouble();String s = stdin.next();
![Page 72: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/72.jpg)
7474
Beware!!!Beware!!!
![Page 73: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/73.jpg)
7676
OverloadingOverloading
![Page 74: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/74.jpg)
77
Overloading Consider the ‘+’ operator
It can mean integer addition: 3+5 = 8 It can mean floating-point addition: 3.0+5.0 = 8.0 It can mean string concatenation: “foo” + “bar” =
“foobar”
The ‘+’ operator has multiple “things” it can do a.k.a. the ‘+’ operator is overloaded
![Page 75: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/75.jpg)
78
More on overloading We’ve seen a number of methods
In the String class: substring(), charAt(), indexOf(), etc. In the Rectangle class: setLocation(), translate()
Consider the substring() method in the String class One version: s.substring(3)
This will return a string from the 4th character on Another version: s.substring (3,6)
This version will return a string from the character at index 3 up to (but not including!) the character at index 6
There are multiple versions of the same method Differentiated by their parameter list
The substring method can take one OR two parameters This is called overloading
![Page 76: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/76.jpg)
79
More on more on overloading Consider the valueOf() method in the String class
String.valueOf (3) The parameter is an int
String.valueOf (3.5) The parameter is a double
String.valueOf (‘3’) The parameter is a char
There are multiple versions of this method Differentiated by their parameter list Thus, the valueOf() method is overloaded
![Page 77: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/77.jpg)
8080
More on methodsMore on methods
![Page 78: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/78.jpg)
81
Accessors Some methods allow us to find out information about an
object In the Rectangle class: getWidth(), getHeight() These methods are called accessors
They allow us to access attributes of the object An accessor is a method that allows us to find out
attributes of object Usually start with get in the method name I won’t use this terminology much, but the book uses it
![Page 79: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/79.jpg)
82
Mutators
Some methods allow us to set information about the object In the Rectangle class: setLocation(), setBounds() These methods are called mutators
They allow us to change (or mutate) the attributes of an object
A mutator is a method that allows us to set attributes of object
Usually start with set in the method name I won’t use this terminology much, but the book uses it
![Page 80: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/80.jpg)
83
Constructors A constructor is a special method called ONLY when you are
creating (or constructing) and object The name of the constructor is ALWAYS the exact same
name as the class
Scanner stdin = new Scanner (System.in); String foo = new String (“hello world”);
There can be overloaded constructors Rectangle r = new Rectangle(); Rectangle s = new Rectangle (1, 2, 3, 4);
![Page 81: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/81.jpg)
84
Calling the Circle constructor To create a Circle object:
Circle c1 = new Circle();
This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point
to the Circle object Calls the constructor with no
parameters (the ‘default’ constructor)
The constructor is always the first method called when creating (or ‘constructing’) an object
c1
Circle
- radius = 0.0- PI = 3.14159…- …
+ Circle()+ Circle (double r)+ …
![Page 82: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/82.jpg)
85
Calling the Circle constructor To create a Circle object:
Circle c1 = new Circle(2.0);
This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point
to the Circle object Calls the constructor with 1
double parameters (the ‘specific’constructor)
The constructor is always the first method called when creating (or ‘constructing’) an object
c1
Circle
- radius = 0.0- PI = 3.14159…- …
+ Circle()+ Circle (double r)+ …
Circle
- radius = 2.0- PI = 3.14159…- …
+ Circle()+ Circle (double r)+ …
![Page 83: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/83.jpg)
86
Constructor varieties The default constructor usually sets the attributes of an
object to default values But that’s not why it’s called default (we’ll get to that
later) The default constructor ALWAYS takes in zero parameters
Thus, there can be only one
A specific constructor sets the attributes of the object to the passed values We’ll get to why it’s called a specific constructor later The specific constructor takes in one or more parameters There can be more than one (via overloading)
![Page 84: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/84.jpg)
87
Method types review With the exception of constructors, these names are purely
for human categorization
Accessor: allows one to access parts of the object Mutator: allows one to change (mutate) a part of an object Constructor: used to create a object
Default constructor: takes in no parameters Specific constructor: takes in one or more parameters
Facilitator Any method that is not one of the above
![Page 85: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/85.jpg)
8888
Today’s demotivatorsToday’s demotivators
![Page 86: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/86.jpg)
8989
Java documentationJava documentation
![Page 87: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/87.jpg)
90
Java documentation
![Page 88: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/88.jpg)
91
Java packages Group similar classes together
Packages we will use: java.lang: automatically imported by Java
Contains the clases needed by the Java language java.util: contains Scanner, Vector, etc.
Contains various utility classes java.text: we will use it later in the semester
Contains classes used to manipulate text
Any package (other than java.lang) must be imported to use the classes within it
![Page 89: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/89.jpg)
9292
Not going over remaining Not going over remaining slides in this setslides in this set
![Page 90: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/90.jpg)
9393
Example: last semester’s HW J2Example: last semester’s HW J2
![Page 91: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/91.jpg)
94
Last semester’s HW J2 Found online at
http://www.cs.virginia.edu/~asb/teaching/cs101-fall05/hws/hwj2/index.html The HW listed 10 steps to be performed
Used the StringBuffer class Which can be found at
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
Strings are immutable Meaning that once you create a String, you can never
change it There are no mutator methods
You can change what the String reference points to, but not the String itself
![Page 92: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/92.jpg)
95
Preliminaries
import java.util.*;
public class StringBufferManipulator { public static void main (String args[]) {
// Preliminaries System.out.println ("StringBuffer manipulator\n"); Scanner stdin = new Scanner (System.in);
// Code for steps 1 to 10 will go here
}}
![Page 93: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/93.jpg)
96
Step 1 The user needs to enter two strings: one long string (say, 10
or so characters at a minimum) and a shorter string that is contained within the longer string. This input should be obtained via the nextLine() method,
as using the next() method will not read in a string that contains spaces.
// Step 1System.out.println ("Enter a long string");String longString = stdin.nextLine();System.out.print ("\nEnter a shorter string within “);System.out.println (“the long string");String shortString = stdin.nextLine();System.out.println ();
![Page 94: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/94.jpg)
97
Step 2 Create a StringBuffer object from the longer string -- this is
the StringBuffer that you will manipulate for the rest of the homework. There are two ways to do this: create a default constructred StringBuffer, and append() the long string to that, or use the StringBuffer with the appropriate specific constructor.
// Step 2StringBuffer buffer = new StringBuffer(longString);
![Page 95: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/95.jpg)
98
Step 3 Include, as a comment in your program, the code for creating
the StringBuffer in the other way from step 2.
// Step 3// StringBuffer buffer = new StringBuffer();// buffer.append(longString();
![Page 96: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/96.jpg)
99
Step 4 Find the position of the small string within the StringBuffer,
and save that position.
// Step 4int pos = buffer.indexOf(shortString);
![Page 97: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/97.jpg)
100100
These images are not These images are not animated…animated…
![Page 98: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/98.jpg)
101
Step 5 Delete the small string from the StringBuffer, and print out
the result.
// Step 5int shortLength = shortString.length();buffer.delete (pos, pos+shortLength);System.out.println (buffer);
![Page 99: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/99.jpg)
102
Step 6 Insert "CS101" into the position of the StringBuffer where the
small string was originally found (from step 3), and print out the result
// Step 6buffer.insert (pos, "CS101");System.out.println (buffer);
![Page 100: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/100.jpg)
103
Step 7 Remove the last word from the string. You can assume that
everything from the last space (found via lastIndexOf()) to the end of the String is the last word. Print out the result.
// Step 7pos = buffer.lastIndexOf(" ");int bufferLength = buffer.length();buffer.delete(pos, bufferLength);System.out.println (buffer);
![Page 101: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/101.jpg)
104
Step 8 Append " rocks" to the end of the StringBuffer, and print out
the result. Note that there is a space before the work 'rocks'.
// Step 8buffer.append (" rocks");System.out.println (buffer);
![Page 102: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/102.jpg)
105
Step 9 Delete the character at position n/2, where n is the length of
the StringBuffer. Print out the result.
// Step 9int n = buffer.length();buffer.deleteCharAt (n/2);System.out.println (buffer);
![Page 103: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/103.jpg)
106
Step 10 Reverse the StringBuffer, and print out the result.
// Step 10buffer.reverse();System.out.println (buffer);
![Page 104: Using Objects](https://reader035.vdocuments.us/reader035/viewer/2022062723/56813c0c550346895da577e6/html5/thumbnails/104.jpg)
107107
Program demoProgram demo
StringBufferManipulator.javaStringBufferManipulator.java