Download wk02.3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 6
Object References
7
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
num1
38
"Steve Jobs"
name1
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 7
Assignment Revisited
8
The act of assignment takes a copy of a value and stores it in
a variable
For primitive types:
Before:
num1
38
num2
96
num2 = num1;
After:
num1
38
num2
38
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 8
Assignment Revisited
9
For object references, the address is copied:
Before:
name1
"Steve Jobs"
name2
"Steve Wozniak"
name2 = name1;
name1
After:
"Steve Jobs"
name2
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 only one object
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 13
Some methods of the String class:
14
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 14
Examples of using String class:
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;
phrase
mutation1
System.out.println("Original string: \"" + phrase + "\"");
System.out.println("Length of string: " + phrase.length());
mutation1
mutation2
mutation3
mutation4
=
=
=
=
"Change is inevitable"
"Change is inevitable, except from vending machines."
phrase.concat(", except from vending machines.");
mutation1.toUpperCase();
mutation2.replace('E', 'X');
mutation3.substring(3, 30);
mutation2
// Print each mutated string
System.out.println("Mutation #1: " + mutation1);
System.out.println("Mutation #2: " + mutation2);
"CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES."
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
SFU
Mutated length: 27, LengthScott
ofKristjanson
phrase– CMPT
is 125/126
now: –20
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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
counter = 1
"1"
"counter = "
1
"counter = "
1
counter++
2
3
2
++counter
counter
= 2
(Initial value)
counter = 3
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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.nextLine();
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 20
Some Scanner class Methods
21
String nextLine()
String
Int
float
Double
next()
nextInt()
nextFloat()
nextDouble()
Boolean hasNext()
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 21
Scanner Class Example
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: Hello Java!
You entered: "Hello Java!"
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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 nextInt and nextDouble read data of
particular types
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 23
Input Tokens Example
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: 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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 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
toUpperCase
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 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 25
References:
26
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
Scott Kristjanson – CMPT 125/126 – SFU
Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase
Wk02.3 Slide 26