Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 2 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 2 Scope  Creating objects  Services of the String class  Introduction to the Scanner class for reading input streams

3 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 3 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 3 Creating Objects 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

4 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 4 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 4 Creating Objects Generally, we use the new operator to create an object: title = new String("James Gosling"); Creating an object is called instantiation Instantiating an object allocates space in memory for it An object is an instance of a particular class This calls the String constructor, which is a special method that creates the object

5 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 5 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 5 Creating Strings 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

6 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 6 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 6 Invoking Methods 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

7 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 7 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 7 Object References A primitive variable like num1 contains the value itself An object variable link name1 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 "Steve Jobs" name1 num138

8 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 8 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 8 Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:

9 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 9 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 9 Assignment Revisited For object references, the address is copied: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs"

10 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 10 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 10 Aliases 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 only one object

11 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 11 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 11 Garbage Collection 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

12 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 12 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 12 The String Class 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

13 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 13 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 13 The String Class 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

14 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 14 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 14 Some methods of the String class:

15 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 15 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 15 public class StringMutation { // Prints a string and various mutations of it. public static void main(String[] args) { String phrase = "Change is inevitable"; String mutation1, mutation2, mutation3, mutation4; System.out.println("Original string: \"" + phrase + "\""); System.out.println("Length of string: " + phrase.length()); mutation1 = phrase.concat(", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace('E', 'X'); mutation4 = mutation3.substring(3, 30); // Print each mutated string System.out.println("Mutation #1: " + mutation1); System.out.println("Mutation #2: " + mutation2); System.out.println("Mutation #3: " + mutation3); System.out.println("Mutation #4: " + mutation4); System.out.println("Mutated length: "+mutation4.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 Mutated length: 27, Length of phrase is now: Examples of using String class: 20 phrase "Change is inevitable" mutation1 "Change is inevitable, except from vending machines." "CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES." mutation2

16 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 16 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 16 Increment and Decrement Revisited 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…

17 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 17 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 17 (Initial value) Why “counter=13”? Let’s work it out… int counter = 1; System.out.println("counter = " + counter++ + ++counter); 1)Use your precedence table to order the operators 2)Create an Expression Evaluation Graph to work it out counter = 1 "counter = "counter++++counter "counter = 1" counter = 2 counter = 3 1 "1""1" concat "3""3" "counter = 13" "counter = " 3 1432 1 4 3 2 2

18 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 18 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 18 The Scanner Class 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

19 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 19 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 19 Reading Input 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.nextLine ();

20 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 20 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 20 Reading Input 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 nextLine method reads all of the input until the end of the line is found answer = scan.nextLine(); We'll discuss class libraries in more detail later

21 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 21 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 21 Some Scanner class Methods StringnextLine() Stringnext() IntnextInt() floatnextFloat() DoublenextDouble() BooleanhasNext()

22 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 22 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 22 //******************************************************************** // Echo.java Java Foundations // // Demonstrates the use of the nextLine 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.nextLine(); System.out.println("You entered: \"" + message + "\""); } } Enter a line of text: You entered: "Hello Java!" Scanner Class Example Hello Java!

23 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 23 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 23 Input Tokens 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 nextInt and nextDouble read data of particular types

24 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 24 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 24 //******************************************************************** // GasMileage.java Java Foundations // // Demonstrates the use of the Scanner class to read numeric data. //******************************************************************** import java.util.Scanner; public class GasMileage { //----------------------------------------------------------------- // 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.nextInt(); System.out.print("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println("Miles Per Gallon: " + mpg); } } Enter the number of miles: Enter the gallons of fuel used: Miles Per Gallon: 40.0 Input Tokens Example 100 2.5

25 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 25 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 25 Key Things to take away: 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 toUpperCase Etc The System.in object represents the standard input stream The Scanner Class provides methods for reading input values

26 Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 26 Scott Kristjanson – CMPT 125/126 – SFU Wk02.3 Slide 26 References: 1.J. Lewis, P. DePasquale, and J. Chase., Java Foundations: Introduction to Program Design & Data Structures. Addison-Wesley, Boston, Massachusetts, 3rd edition, 2014, ISBN 978-0-13-337046-1


Download ppt "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."

Similar presentations


Ads by Google