Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section...
-
Upload
aubrey-tyler -
Category
Documents
-
view
233 -
download
0
Transcript of Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section...
Using Classes and ObjectsChapters 3Creating Objects – Section 3.1The String Class – Section 3.2The Scanner Class – Section 2.6
Instructor: Scott Kristjanson
CMPT 125/125
SFU Burnaby, Fall 2013
Wk02.3 Slide 2Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
2
Scott Kristjanson – CMPT 125/126 – SFU
Scope
Creating objects Services of the String class Introduction to the Scanner class for reading input streams
Wk02.3 Slide 3Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
3
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 4Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
4
Scott Kristjanson – CMPT 125/126 – SFU
Creating Objects
Generally, we use the new operator to create an object:
title = new String("James Gosling");
Creating an object is called instantiationInstantiating an object allocates space in memory for itAn object is an instance of a particular class
This calls the String constructor, which isa special method that creates the object
Wk02.3 Slide 5Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
5
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 6Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
6
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 7Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
7
Scott Kristjanson – CMPT 125/126 – SFU
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
num1 38
Wk02.3 Slide 8Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
8
Scott Kristjanson – CMPT 125/126 – SFU
Assignment Revisited
The act of assignment takes a copy of a value and stores it in a variable
For primitive types:
num1 38
num2 96Before:
num2 = num1;
num1 38
num2 38After:
Wk02.3 Slide 9Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
9
Scott Kristjanson – CMPT 125/126 – SFU
Assignment Revisited
For object references, the address is copied:
name2 = name1;
name1
name2Before:
"Steve Jobs"
"Steve Wozniak"
name1
name2After:
"Steve Jobs"
Wk02.3 Slide 10Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
10
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 11Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
11
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 12Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
12
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 13Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
13
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 14Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
14
Scott Kristjanson – CMPT 125/126 – SFU
Some methods of the String class:
Wk02.3 Slide 15Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
15
Scott Kristjanson – CMPT 125/126 – SFU
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: 20Mutation #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 FMutated 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
Wk02.3 Slide 16Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
16
Scott Kristjanson – CMPT 125/126 – SFU
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 = 13Why 13? Does counter now equal 13?Of course not! Let’s work it out…
Wk02.3 Slide 17Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
17
Scott Kristjanson – CMPT 125/126 – SFU
(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 operators2) Create an Expression Evaluation Graph to work it out
counter = 1
"counter = " counter++ ++counter
"counter = 1"
counter = 2
counter = 3
1
"1"
concat
concat
"3"
"counter = 13"
"counter = "
3
1 43 2
1
4
3
2
2
Wk02.3 Slide 18Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
18
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 19Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
19
Scott Kristjanson – CMPT 125/126 – SFU
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();
Wk02.3 Slide 20Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
20
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 21Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
21
Scott Kristjanson – CMPT 125/126 – SFU
Some Scanner class Methods
String nextLine()
String next()Int nextInt()float nextFloat()DoublenextDouble()
Boolean hasNext()
Wk02.3 Slide 22Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
22
Scott Kristjanson – CMPT 125/126 – SFU
//********************************************************************// 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!
Wk02.3 Slide 23Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
23
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 24Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
24
Scott Kristjanson – CMPT 125/126 – SFU
//********************************************************************// 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
1002.5
Wk02.3 Slide 25Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
25
Scott Kristjanson – CMPT 125/126 – SFU
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
Wk02.3 Slide 26Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
26
Scott Kristjanson – CMPT 125/126 – SFU
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