Using Objects Chapter 3 Fall 2006 CS 101
Using Objects Chapter 3 Fall 2006 CS 101 Aaron Bloomfield 1
Getting classy o o Purpose of this chapter n Gain experience creating and manipulating objects from the standard Java types Why n Prepares you for defining your own classes and creating and manipulating the objects of those classes 2
Values versus objects o o Numbers n Have values but they do not have behaviors n In particular, each has only ONE value (or attribute) Objects n Have attributes and behaviors n An object can have multiple values (or attributes) 3
Using objects o o First, we create an object: n Scanner stdin = new Scanner (System. in); Most object creation lines look like this Then we use the object n stdin. next. Int(); n stdin. next. Double(); Note that we could have called the object foo, bar, or anything n stdin is just what we chose to call it 4
Using Rectangle objects o o Let’s create some Rectangle objects Rectangle creation: n Rectangle r = new Rectangle (10, 20); Objects have attributes (or properties): n System. out. println (r. width); n System. out. println (r. height); Objects have behaviors (or methods): n r. grow (10, 20); n r. is. Empty(); n r. set. Location (5, 4); 5
Using String objects o o Let’s create some String objects String creation: n String s = new String (“Hello world”); Objects have attributes (or properties): n But we can’t access them… Objects have behaviors (or methods): n s. substring(0, 6); n s. index. Of (“world”); n s. to. Lower. Case(); 6
The lowdown on objects o Objects are “things” that have properties (attributes) and behaviors (methods) o We first create one or more objects o We then manipulate their properties and call their methods 7
So why bother with objects? o o o 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 n Sun already wrote the methods for us So we can use String objects instead of writing our own code to get the substring, index. Of, etc. 8
More on Strings o o Strings are used very often As a shortcut, you can use: n String s = “Hello world”; instead of: n String s = new String (“Hello world”); It’s just a shortcut that Java allows The two lines are almost the same n There is a minor difference between the two o Which we’ll get to later 9
Visualizing objects Rectangle - width = 10 - height = 20 -. . . + grow (int, int) : void + is. Empty ( ) : void + set. Location ( int, int ) : void + resize ( int, int ) : void +. . . o Class (type) name o Attributes (properties) o Methods (behaviors) 10
How well do we understand using objects? 11
For Valentine’s Day… 12
Bittersweets: Dejected sayings n. I MISS MY EX n PEAKED AT 17 n MAIL ORDER n TABLE FOR 1 n I CRY ON Q n U C MY BLOG? n REJECT PILE n PILLOW HUGGIN n ASYLUM BOUND n DIGNITY FREE n PROG FAN n STATIC CLING n WE HAD PLANS n XANADU 2 NITE n SETTLE 4 LESS n NOT AGAIN 13
Bittersweets: Dysfunctional sayings n RUMORS TRUE n PRENUP OKAY? n HE CAN LISTEN n GAME ON TV n CALL A 900# n P. S. I LUV ME n DO MY DISHES n UWATCH CMT n PAROLE IS UP! n BE MY YOKO n U+ME=GRIEF n I WANT HALF n RETURN 2 PIT n NOT MY MOMMY n BE MY PRISON n C THAT DOOR? 14
Review o o Variables of primitive types n int, double, char, boolean, etc. n Can assign a value to it n Can read a value from it n Can’t do much else! Objects n String, Rectangle, etc. n Have many parts o Rectangle has width, length, etc. n Like a complex type n Have methods o String has length(), substring(), etc. 15
String methods o length(): returns the String’s length (duh!) String s = “hello world”; String t = “goodbye”; System. out. println (s. length()); System. out. println (t. length()); o o Prints 11 and 7 Note that calling s. length() is different than calling t. length()! n Both return the length n But of different Strings 16
More String methods o o Consider String wedding. Date = "August 21, 1976"; String month = wedding. Date. substring(0, 6); System. out. println("Month is " + month + ". "); What is the output? Month is August. 17
More String methods o Consider String fruit = "banana"; String search. String = "an"; int n 1 = fruit. index. Of(search. String, 0); int n 2 = fruit. index. Of(search. String, n 1 + 1); int n 3 = fruit. index. Of(search. String, n 2 + 1); System. out. println("First search: " + n 1); System. out. println("Second search: " + n 2); System. out. println("Third search: " + n 3); o What is the output? First search: 1 Second search: 3 Third search: -1 18
String program examples 20
Program Word. Length. java public class Word. Length { public static void main(String[] args) { Scanner stdin = new Scanner(System. in); System. out. print("Enter a word: "); String word = stdin. next(); int word. Length = word. length(); System. out. println("Word " + word + " has length " + word. Length + ". "); } } 21
Program demo n Word. Length. java 22
More String methods o trim() n Returns the String without leading and trailing whitespace n Whitespace is a space, tab, or return 23
Date translation o Goal: to translate the date from American format to standard format 24
Date. Translation. java // Convert user-specified date from American to standard format import java. util. *; class Date. Translation { // 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) } } 25
Program demo n Date. Translation. java 26
Today’s demotivators 27
Classes vs. Objects 28
Variables vs. Types o o o The type is the recipe or template for how to create a variable n Examples: int, double, char, boolean, etc. o There are only 8 primitive types n There are only a few things you can do with a type: o Declare a variable n int x; o Use it as a cast n x = (int) 3. 5; n There is only one of each type The variable is the actual instance of a type in memory n It’s a spot in memory where you store a value n You choose the name: width, x, that. Them. There. Value, etc. n You can have as may variables as you want – but only one type! Like the difference between a recipe and a bunch of cookies 29
How well do we understand variables versus types? 30
Classes vs. Objects o o o A class is a user-defined “thing” n Examples: String, Scanner, Rectangle, etc. o We’ll start defining our own classes later this semester n Classes are more complex than the primitive types n A class is analogous to a type o It’s just more complex and user-defined n There can be only one class of each name An object is an instance of a class n There is only one String class, but you can have 100 String objects n A object is analogous to a variable o It just is a reference instead A class is a “template” used for creating objects 31
More on classes vs. objects 32
How well do we understand classes versus objects? 33
Lots of piercings… This may be a bit disturbing… 34
References 35
Java and variables o o o 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 Note that d does not have a value 36
What is a reference o o o A reference is a memory address References are like pointers in C/C++ n But they are not the exact same thing! n C++ has references also (in addition to pointers) n You may hear me call them pointers instead of references All objects in Java are declared as references 37
References 1 o o 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 now) 38
References 2 o What’s happening in memory int j = 5; String s = “Hello world”; String s 0 x 0 d 4 fe 1 a 8 Takes up 32 bits (4 bytes) of memory int j 5 At memory location 0 x 0 d 4 fe 1 a 8 Takes up 12 bytes of memory o Hello world Primitive types are never references; only objects 39
Representation o Statements int peas. Per. Pod = 8; String message = "Don't look behind the door!“ message peas. Per. Pod 8 String - text = "Don't look behind the door!" - length = 27 -. . . + length () : int + char. At ( int i ) : char + sub. String ( int m, int n ) : String + index. Of ( String s, int m ) : int +. . . 40
Representation String s = “I love CS 101”; int l = s. length(); char c = s. char. At (3); String t = s. sub. String(1, 2); int t = s. index. Of (t, 0); s String A period means “follow the reference” - text = “I love CS 101" - length = 13 -. . . + length () : int + char. At ( int i ) : char + sub. String ( int m, int n ) : String + index. Of ( String s, int m ) : int +. . . 41
Shorthand represntation o o o Consider: String s = “Hello world”; Takes up a lot of space on my slides… So we’ll use a shorthand representation: s s String - text = “Hello world" - length = 11 -. . . + length () : int + char. At ( int i ) : char + sub. String ( int m, int n ) : String + index. Of ( String s, int m ) : int +. . . “Hello world" 42
Examples o o Consider String a = "excellence“; String b = a; What is the representation? 43
References 3 o Consider: String s 1 = “first string”; String s 2 = “second string”; s 2 = s 1; System. out. println (s 2); What happens to this? String s 1 “first string” “second string” String s 2 45
Java’s garbage collection o If an object in memory does not have a reference pointing to it, Java will automagically delete the object o This is really cool! o In C/C++, you had to do this by yourself 46
An optical illusion 47
The null reference 48
Uninitialized versus null o o Consider String day. Of. Week; Scanner in. Stream; What is the representation? 49
Uninitialized versus null o o Consider String font. Name = null; Scanner file. Stream = null; What is the representation? font. Name null file. Stream null OR font. Name file. Stream 50
The null reference o o o 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 (0 x 0000) n No user program can exist there 51
The null reference o o Consider: String s = “Hello world”; System. out. println (s. length()); What happens? n Java prints out 11 s String - text = “Hello world" - length = 11 -. . . + length () : int + char. At ( int i ) : char + sub. String ( int m, int n ) : String + index. Of ( String s, int m ) : int +. . . 52
The null reference o o o Consider: String s = null; System. out. println (s. length()); This is called accessing (or following) a null pointer/reference What happens? n Java: java. lang. Null. Pointer. Exception n C/C++: Segmentation fault (core dumped) n Windows: … 53
What happens in Windows… 54
So what is a null reference good for? o Let’s say you had a method that returned a String when passed some parameters n Normally it returns a valid String o But what if it can’t? How to deal with that? o Return a null reference 55
References and memory o o o Most modern computers are 32 -bit computers n This means that a reference takes up 32 bits n 232 = 4 Gb This means that a 32 -bit machine cannot access more than 4 Gb of memory! n Well, without doing some “tricks”, at least n Most machines come with 1 Gb memory these days n Will come with 4 Gb in a year or so 64 -bit machines will have a maximum of 16 exabytes of memory n Giga, Tera, Peta, Exa n That’s 16 billion Gb! 56
The 2004 Ig Nobel Prizes Medicine n Physics n Public Health n Chemistry n Engineering n Literature n Psychology n Economics n Peace n n Biology "The Effect of Country Music on Suicide. “ For explaining the dynamics of hula-hooping Investigating the scientific validity of the Five. Second Rule The Coca-Cola Company of Great Britain For the patent of the combover The American Nudist Research Library It’s easy to overlook things – even a man in a gorilla suit. The Vatican, for outsourcing prayers to India The invention of karaoke, thereby providing an entirely new way for people to learn to tolerate each other For showing that herrings apparently communicate 57 by farting
Using object examples 58
Assignment o o Consider String word 1 = "luminous"; String word 2 = "graceful"; word 1 = word 2; Garbage collection time! Initial representation word 1 "luminous" word 2 "graceful" 59
Using objects o o 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: 60
String representation o Consider n String alphabet = "abcdefghijklmnopqrstuvwxyz"; o Standard shorthand representation o Truer representation 61
String representation o o Consider n String alphabet = "abcdefghijklmnopqrstuvwxyz"; n char c 1 = alphabet. char. At(9); n char c 2 = alphabet. char. At(15); n char c 3 = alphabet. char. At(2); What are the values of c 1, c 2, and c 3? Why? 62
More String methods o Consider int v 1 = -12; double v 2 = 3. 14; char v 3 = 'a'; String s 1 = String. value. Of(v 1); String s 2 = String. value. Of(v 2); String s 3 = String. value. Of(v 3); v 1 -12 v 2 3. 14 v 3 ‘a’ s 1 "-12" s 2 "3. 14" s 3 "a" 63
Final variables o o Consider final String POEM_TITLE = “Appearance of Brown"; final String WARNING = “Weather ball is black"; What is the representation? 64
Final variables o Consider final String LANGUAGE = "Java"; The reference cannot be modified once it is established LANGUAGE "Java" 65
Today’s demotivators 66
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); The dimensions of the new Rectangle 67
Rectangle o Consider final Rectangle BLOCK = new Rectangle(6, 9, 4, 2); BLOCK. set. Location(1, 4); BLOCK. resize(8, 3); 68
String method usage o y 4 x 10 Consider: String s = "Halloween"; String t = "Groundhog Day"; v String u = "May Day"; String v = s. substring(0, 6); “Hallow" int x = t. index. Of ("Day", 0); int y = u. index. Of ("Day"); String s = t; - text = “May “Halloween" “Groundhog Day" u = null; s “Halloween" t “Groundhog Day" u “May Day" - length = 7 9 13 -. . . + length () : int + sub. String ( int m, int n ) : String + index. Of ( String s, int m ) : int + index. Of ( String s ) : int 69 +. . .
String method usage o x Consider: String s = "Halloween"; String t = "Groundhog Day"; final String u = "May Day"; String v = s. substring(0, 6); int x = t. index. Of ("Day", 0); int y = u. index. Of ("Day"); s = t; u = null; s “Halloween" t “Groundhog Day" u “May Day" 10 y 4 v “Hallow" Java error: cannot assign a value to final variable u 70
Rectangle method usage o Consider: Rectangle - width = 1 7 - height = 2 Rectangle r = new Rectangle(); final Rectangle s = new Rectangle (3, 4, 1, 2); s r. set. Width(5); r. set. Height(6); r s. set. Width (7); r = new Rectangle (10, 11, 8, 9); s = new Rectangle (12, 13, 14, 15); Rectangle - width = 8 - height = 9 - x = 10 - y = 11 -x=3 -y=4 + set. Width ( int w ) + set. Height ( int wh ) + set. X ( int x ) + set. Y ( int y ) +. . . Rectangle - width = 0 5 - height = 0 6 -x=0 -y=0 + set. Width ( int w ) + set. Height ( int wh ) + set. X ( int x ) + set. Y ( int y ) 71 +. . .
Scanner review o o To initialize a Scanner object: n Scanner stdin = new Scanner (System. in); n Scanner stdin = Scanner. create (System. in); o This one will not work! To read an int from the keyboard: n stdin. next. Int(); To read a double from the keyboard: n stdin. next. Double(); To read a String from the keyboard: n stdin. next(); 72
Scanner usage examples o Consider: Scanner stdin = new Scanner (System. in); int x = stdin. next. Int(); double d = stdin. next. Double(); String s = stdin. next(); stdin x s Scanner: 5 d 3. 5 “hello world” 73
Beware!!! 74
Overloading 76
Overloading o o Consider the ‘+’ operator n It can mean integer addition: 3+5 = 8 n It can mean floating-point addition: 3. 0+5. 0 = 8. 0 n It can mean string concatenation: “foo” + “bar” = “foobar” The ‘+’ operator has multiple “things” it can do n a. k. a. the ‘+’ operator is overloaded 77
More on overloading o o We’ve seen a number of methods n In the String class: substring(), char. At(), index. Of(), etc. n In the Rectangle class: set. Location(), translate() Consider the substring() method in the String class n One version: s. substring(3) o This will return a string from the 4 th character on n Another version: s. substring (3, 6) o This version will return a string from the character at index 3 up to (but not including!) the character at index 6 n There are multiple versions of the same method o Differentiated by their parameter list n The substring method can take one OR two parameters 78 o This is called overloading
More on more on overloading o o Consider the value. Of() method in the String class n String. value. Of (3) o The parameter is an int n String. value. Of (3. 5) o The parameter is a double n String. value. Of (‘ 3’) o The parameter is a char There are multiple versions of this method n Differentiated by their parameter list n Thus, the value. Of() method is overloaded 79
More on methods 80
Accessors o Some methods allow us to find out information about an object n In the Rectangle class: get. Width(), get. Height() n These methods are called accessors o They allow us to access attributes of the object n An accessor is a method that allows us to find out attributes of object n Usually start with get in the method name n I won’t use this terminology much, but the book uses it 81
Mutators Some methods allow us to set information about the object n In the Rectangle class: set. Location(), set. Bounds() n These methods are called mutators o They allow us to change (or mutate) the attributes of an object n A mutator is a method that allows us to set attributes of object n Usually start with set in the method name n I won’t use this terminology much, but the book uses it 82
Constructors o A constructor is a special method called ONLY when you are creating (or constructing) and object n The name of the constructor is ALWAYS the exact same name as the class n n o Scanner stdin = new Scanner (System. in); String foo = new String (“hello world”); There can be overloaded constructors n Rectangle r = new Rectangle(); n Rectangle s = new Rectangle (1, 2, 3, 4); 83
Calling the Circle constructor o To create a Circle object: c 1 Circle c 1 = new Circle(); o o This does four things: n Creates the c 1 reference n Creates the Circle object n Makes the c 1 reference point to the Circle object n Calls the constructor with no parameters (the ‘default’ constructor) Circle - radius = 0. 0 - PI = 3. 14159… -… + Circle() + Circle (double r) +… The constructor is always the first method called when creating (or ‘constructing’) an object 84
Calling the Circle constructor o To create a Circle object: c 1 Circle c 1 = new Circle(2. 0); o o This does four things: n Creates the c 1 reference n Creates the Circle object n Makes the c 1 reference point to the Circle object n Calls the constructor with 1 double parameters (the ‘specific’ constructor) Circle - radius = 2. 0 0. 0 - PI = 3. 14159… -… + Circle() + Circle (double r) +… The constructor is always the first method called when creating (or ‘constructing’) an object 85
Constructor varieties o o The default constructor usually sets the attributes of an object to default values n But that’s not why it’s called default (we’ll get to that later) n The default constructor ALWAYS takes in zero parameters o Thus, there can be only one A specific constructor sets the attributes of the object to the passed values n We’ll get to why it’s called a specific constructor later n The specific constructor takes in one or more parameters n There can be more than one (via overloading) 86
Method types review o o o 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 n Default constructor: takes in no parameters n Specific constructor: takes in one or more parameters Facilitator n Any method that is not one of the above 87
Today’s demotivators 88
Java documentation 89
Java documentation 90
Java packages o o o Group similar classes together Packages we will use: n java. lang: automatically imported by Java o Contains the clases needed by the Java language n java. util: contains Scanner, Vector, etc. o Contains various utility classes n java. text: we will use it later in the semester o Contains classes used to manipulate text Any package (other than java. lang) must be imported to use the classes within it 91
Not going over remaining slides in this set 92
Example: last semester’s HW J 2 93
Last semester’s HW J 2 o o o Found online at http: //www. cs. virginia. edu/~asb/teaching/cs 101 fall 05/hws/hwj 2/index. html n The HW listed 10 steps to be performed Used the String. Buffer class n Which can be found at http: //java. sun. com/j 2 se/1. 5. 0/docs/api/java/lang/String Buffer. html Strings are immutable n Meaning that once you create a String, you can never change it o There are no mutator methods n You can change what the String reference points to, but 94 not the String itself
Preliminaries import java. util. *; public class String. Buffer. Manipulator { public static void main (String args[]) { // Preliminaries System. out. println ("String. Buffer manipulatorn"); Scanner stdin = new Scanner (System. in); // Code for steps 1 to 10 will go here } } 95
Step 1 o 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. n This input should be obtained via the next. Line() method, as using the next() method will not read in a string that contains spaces. // Step 1 System. out. println ("Enter a long string"); String long. String = stdin. next. Line(); System. out. print ("n. Enter a shorter string within “); System. out. println (“the long string"); String short. String = stdin. next. Line(); 96 System. out. println ();
Step 2 o Create a String. Buffer object from the longer string -- this is the String. Buffer that you will manipulate for the rest of the homework. There are two ways to do this: create a default constructred String. Buffer, and append() the long string to that, or use the String. Buffer with the appropriate specific constructor. // Step 2 String. Buffer buffer = new String. Buffer(long. String); 97
Step 3 o Include, as a comment in your program, the code for creating the String. Buffer in the other way from step 2. // Step 3 // String. Buffer buffer = new String. Buffer(); // buffer. append(long. String(); 98
Step 4 o Find the position of the small string within the String. Buffer, and save that position. // Step 4 int pos = buffer. index. Of(short. String); 99
These images are not animated… 100
Step 5 o Delete the small string from the String. Buffer, and print out the result. // Step 5 int short. Length = short. String. length(); buffer. delete (pos, pos+short. Length); System. out. println (buffer); 101
Step 6 o Insert "CS 101" into the position of the String. Buffer where the small string was originally found (from step 3), and print out the result // Step 6 buffer. insert (pos, "CS 101"); System. out. println (buffer); 102
Step 7 o Remove the last word from the string. You can assume that everything from the last space (found via last. Index. Of()) to the end of the String is the last word. Print out the result. // Step 7 pos = buffer. last. Index. Of(" "); int buffer. Length = buffer. length(); buffer. delete(pos, buffer. Length); System. out. println (buffer); 103
Step 8 o Append " rocks" to the end of the String. Buffer, and print out the result. Note that there is a space before the work 'rocks'. // Step 8 buffer. append (" rocks"); System. out. println (buffer); 104
Step 9 o Delete the character at position n/2, where n is the length of the String. Buffer. Print out the result. // Step 9 int n = buffer. length(); buffer. delete. Char. At (n/2); System. out. println (buffer); 105
Step 10 o Reverse the String. Buffer, and print out the result. // Step 10 buffer. reverse(); System. out. println (buffer); 106
Program demo n String. Buffer. Manipulator. java 107
- Slides: 104