1 / 110

Using Objects

Using Objects. Chapter 3 Fall 2005 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.

tate-quinn
Download Presentation

Using Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Using Objects Chapter 3 Fall 2005 CS 101 Aaron Bloomfield

  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

  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. 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

  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.length); • System.out.println (r.width); • Objects have behaviors (or methods): • r.grow (10, 20) • r.isEmpty() • r.setLocation (5,4)

  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()

  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

  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.

  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

  10. Class (type) name Attributes (properties) Methods (behaviors) Rectangle - width = 10 - height = 20 - ... + grow (int, int) : void + isEmpty ( ) : void + setLocation ( int, int ) : void + resize ( int, int ) : void + ... Visualizing objects

  11. Date translation • Goal: to translate the date from American format to standard format

  12. How well do we understand using objects?

  13. Sidewalk chalk guy • Source: http://www.gprime.net/images/sidewalkchalkguy/

  14. int x double d char c 7 - ‘x’ 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

  15. 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

  16. 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 this lecture) Note that there is no “new” here

  17. 0x0d4fe1a8 int j Hello world 5 References 2 int j = 5; String s = “Hello world”; • What’s happening in memory int j = 5; String s = “Hello world”; • Primitive types are never references; only objects String s Takes up 32 bits (4 bytes) of memory Takes up 32 bits (4 bytes) of memory At memory location 0x0d4fe1a8 Takes up 12 bytes of memory

  18. Other Java object types • String • Rectangle • Color • JFrame

  19. peasPerPod 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 + ... Representation • Statements int peasPerPod = 8; String message = "Don't look behind the door!“

  20. s String - text = “I love CS 101" - length = 13 - ... + length () : int + charAt ( int i ) : char + subString ( int m, int n ) : String + indexOf ( String s, int m ) : int + ... 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);

  21. Shorthand representation • Statements int peasPerPod = 8; String message = "Don't look behind the door!“

  22. Examples • Consider String a = "excellence“; String b = a; • What is the representation?

  23. Uninitialized versus null • Consider String dayOfWeek; Scanner inStream; • What is the representation?

  24. fontName fontName null null fileStream fileStream Uninitialized versus null • Consider String fontName = null; Scanner fileStream = null; • What is the representation? OR

  25. 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

  26. 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 + ... The null reference • Consider: String s = “Hello world”; System.out.println (s.length()); • What happens? • Java prints out 11

  27. Computer bugs

  28. 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: …

  29. 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

  30. 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!

  31. String s1 “first string” “second string” String s2 length = 12 length = 13 References 4 String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); • Consider: String s1 = “first string”; String s2 = “second string”; s2 = s1; System.out.println (s2); What happens to this?

  32. 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

  33. word1 "luminous" word2 "graceful" Assignment • Consider String word1 = "luminous"; String word2 = "graceful"; word1 = word2; • Initial representation Garbage collection time!

  34. reponse "artiste" stdin Scanner: 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

  35. String representation • Consider • String alphabet = "abcdefghijklmnopqrstuvwxyz"; • Standard shorthand representation • Truer representation

  36. 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?

  37. 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 + "haslength" + wordLength + "."); } }

  38. Program demo

  39. An optical illusion

  40. 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.

  41. 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

  42. 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.

  43. Variable declaration • Consider: • int x = 5; • int x = 7; • Java won’t allow this • You can only declare a variable once • At the int x=7; line, Java already has a x spot in memory • It can’t have two

  44. 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

  45. 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.

  46. 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

  47. 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 + "haslength" + wordLength + "."); } }

  48. Program demo

  49. PhoneNumberFun.java import java.util.*; public class PhoneNumberFun { // main(): demonstrates a simple String manipulation public static void main(String[] args) { //... // determine the area code // determine the local number // arrange result // display input and result } }

  50. Program demo

More Related