Using Classes and Objects Chapters 3 Creating Objects
Using Classes and Objects Chapters 3 Creating Objects – Section 3. 1 The String Class – Section 3. 2 The Scanner Class – Section 2. 6 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Scope 2 § Creating objects § Services of the String class § Introduction to the Scanner class for reading input streams Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 2
Creating Objects 3 A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference variable String title; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 3
Creating Objects 4 Generally, we use the new operator to create an object: title = new String("James Gosling"); This calls the String constructor, which is a special method that creates the object Creating an object is called instantiation Instantiating an object allocates space in memory for it An object is an instance of a particular class Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 4
Creating Strings 5 Because strings are so common, we don't have to use the new operator to create a String object title = "Java rocks!"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 5
Invoking Methods 6 We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods System. out. println(“I am invoking method println”); A method may return a value, which can be used in an assignment or expression count = title. length() A method invocation can be thought of as asking an object to perform a service Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 6
Object References 7 A primitive variable like num 1 contains the value itself An object variable link name 1 contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically num 1 38 "Steve Jobs" name 1 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 7
Assignment Revisited 8 The act of assignment takes a copy of a value and stores it in a variable For primitive types: Before: num 1 38 num 2 96 num 2 = num 1; After: num 1 38 num 2 38 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 8
Assignment Revisited 9 For object references, the address is copied: Before: name 1 "Steve Jobs" name 2 "Steve Wozniak" name 2 = name 1; After: name 1 "Steve Jobs" name 2 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 9
Aliases 10 Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really one object Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 10
Garbage Collection 11 When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection explicitly Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 11
The String Class 12 Once a String object has been created, neither its value nor its length can be changed Thus we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 12
The String Class 13 It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 13
Some methods of the String class: 14 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 14
Examples of using String class: 15 public class String. Mutation { // Prints a string and various mutations of it. public static void main(String[] args) { String phrase = "Change is inevitable"; String mutation 1, mutation 2, mutation 3, mutation 4; phrase mutation 1 System. out. println("Original string: "" + phrase + """); System. out. println("Length of string: " + phrase. length()); mutation 1 mutation 2 mutation 3 mutation 4 = = "Change is inevitable" "Change is inevitable, except from vending machines. " phrase. concat(", except from vending machines. "); mutation 1. to. Upper. Case(); mutation 2. replace('E', 'X'); mutation 3. substring(3, 30); mutation 2 // Print each mutated string System. out. println("Mutation #1: " + mutation 1); System. out. println("Mutation #2: " + mutation 2); "CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. " System. out. println("Mutation #3: " + mutation 3); System. out. println("Mutation #4: " + mutation 4); System. out. println("Mutated length: "+mutation 4. length()+", Length of phrase is now: “+phrase. length()); } } Original string: "Change is inevitable" Length of string: 20 Mutation #1: Change is inevitable, except from vending machines. Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS. Mutation #4: NGX IS INXVITABLX, XXCXPT F – CMPT – SFU Mutated length: 27, Length. Scott of. Kristjanson phrase is 125/126 now: 20 Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 15
Increment and Decrement Revisited 16 The increment and decrement operators can be applied in two forms: Postfix: counter++; // Increment counter after returning its value Prefix: ++counter; // Increment counter before returning its value When used as part of a larger expression, the two forms can have very different effects What is the output from this code fragment? int counter = 1; System. out. println("counter = " + counter++ + ++counter); counter = 13 Why 13? Does counter now equal 13? Of course not! Let’s work it out… Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 16
Why “counter=13”? Let’s work it out… 17 int counter = 1; System. out. println("counter = " + counter++ + ++counter); 3 1) 2) 1 4 2 Use your precedence table to order the operators Create an Expression Evaluation Graph to work it out "counter = 13" 4 concat "3" "counter = 1" 3 concat "1" "counter = " counter = 1 1 "counter = " 1 counter++ 2 2 ++counter 3 counter = 2 (Initial value) counter = 3 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 17
The Scanner Class 18 The Scanner class provides convenient methods for reading input values of various types A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard Keyboard input is represented by the System. in object Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 18
Reading Input 19 The following line creates a Scanner object that reads from the keyboard Scanner scan = new Scanner(System. in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as answer = scan. next. Line(); Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 19
Reading Input 20 The Scanner class is part of the java. util class library, and must be imported into a program to be used import java. util. Scanner; The next. Line method reads all of the input until the end of the line is found answer = scan. next. Line(); We'll discuss class libraries in more detail later Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 20
Some Scanner class Methods 21 String next. Line() String Int float Double next() next. Int() next. Float() next. Double() Boolean has. Next() Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 21
Scanner Class Example 22 //********************************** // Echo. java Java Foundations // // Demonstrates the use of the next. Line method of the Scanner class // to read a string from the user. //********************************** import java. util. Scanner; public class Echo { //--------------------------------// Reads a character string from the user and prints it. //--------------------------------public static void main(String[] args) { String message; Scanner scan = new Scanner(System. in); System. out. print("Enter a line of text: "); message = scan. next. Line(); System. out. println("You entered: "" + message + """); } } Enter a line of text: Hello Java! You entered: "Hello Java!" Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 22
Input Tokens 23 Unless specified otherwise, white space is used to separate the elements (called tokens) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as next. Int and next. Double read data of particular types Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 23
Input Tokens Example 24 //********************************** // Gas. Mileage. java Java Foundations // // Demonstrates the use of the Scanner class to read numeric data. //********************************** import java. util. Scanner; public class Gas. Mileage { //--------------------------------// Calculates fuel efficiency based on values entered by the // user. //--------------------------------public static void main(String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner(System. in); System. out. print("Enter the number of miles: "); miles = scan. next. Int(); System. out. print("Enter the gallons of fuel used: "); gallons = scan. next. Double(); mpg = miles / gallons; System. out. println("Miles Per Gallon: " + mpg); } } Enter the number of miles: 100 Enter the gallons of fuel used: 2. 5 Miles Per Gallon: 40. 0 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 24
Key Things to take away: 25 • Object declarations create place holders which point to an object in memory • The new operator instantiates a new instance of the class • Strings are immutable – changing a string creates a new instance • • A variable holds either a primitive type or a reference to an object Assigning variables of primitive types copies the value Assigning variables of class types copies a reference to the object The String class provides useful methods for working with strings • • • length concat substring to. Upper. Case Etc • The System. in object represents the standard input stream • The Scanner Class provides methods for reading input values Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 25
References: 26 1. J. Lewis, P. De. Pasquale, and J. Chase. , Java Foundations: Introduction to Program Design & Data Structures. Addison-Wesley, Boston, Massachusetts, 3 rd edition, 2014, ISBN 978 -0 -13 -337046 -1 Scott Kristjanson – CMPT 125/126 – SFU Slides based on Java Foundations 3 rd Edition, Lewis/De. Pasquale/Chase 26
- Slides: 26