Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Similar documents
Using Classes and Objects. Chapter

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Using Classes and Objects

Data Conversion & Scanner Class

Introduction to Java (All the Basic Stuff)

Chapter. Let's explore some other fundamental programming concepts

Packages & Random and Math Classes

ing execution. That way, new results can be computed each time the Class The Scanner

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

2: Basics of Java Programming

H212 Introduction to Software Systems Honors

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Formatting Output & Enumerated Types & Wrapper Classes

Java Basic Introduction, Classes and Objects SEEM

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

A variable is a name for a location in memory A variable must be declared

Chapter 2: Data and Expressions

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 2: Data and Expressions

Java Basic Introduction, Classes and Objects SEEM

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Computational Expression

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Linked Structures Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

We now start exploring some key elements of the Java programming language and ways of performing I/O

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Bonus Puzzle #1 Random Doubles [0,5] Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

AP Computer Science Unit 1. Programs

Programming with Java

Using Java Classes Fall 2018 Margaret Reid-Miller

Classes and Objects Part 1

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

Arrays Chapter 7. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Full file at

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Computational Expression

A token is a sequence of characters not including any whitespace.

Fundamentals of Programming Data Types & Methods

A+ Computer Science -

Chapter 4. Mathematical Functions, Characters, and Strings

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

AP Computer Science Unit 1. Writing Programs Using BlueJ

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Analysis of Algorithms Chapter 11. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Chapter 3 Using Classes and Objects

Java Coding 3. Over & over again!

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Objects and Classes -- Introduction

COMP 202 Java in one week

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Basic Computation. Chapter 2

Elementary Programming

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Graphs Chapter 24. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Peer Instruction 1. Elementary Programming

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Midterms Save the Dates!

Object Oriented Programming. Java-Lecture 1

Reading Input from Text File

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSC 1051 Data Structures and Algorithms I

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CMPT 125: Lecture 3 Data and Expressions

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

A Quick and Dirty Overview of Java and. Java Programming

MIDTERM REVIEW. midterminformation.htm

Linked Structures - Review Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSC 1051 Data Structures and Algorithms I

Basic Computation. Chapter 2

CS111: PROGRAMMING LANGUAGE II

Lecture Set 2: Starting Java

Lecture 8 " INPUT " Instructor: Craig Duckett

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Lecture Set 2: Starting Java

Chapter 4: Loops and Files

Introduction to Java Unit 1. Using BlueJ to Write Programs

CMPT 125: Lecture 4 Conditionals and Loops

COMP 202. Java in one week

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 4: Loops and Files

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Transcription:

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 Scope Creating objects Services of the String class Introduction to the Scanner class for reading input streams Wk02.3 Slide 2

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 Wk02.3 Slide 3

4 Creating Objects 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 Wk02.3 Slide 4

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 Wk02.3 Slide 5

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 Wk02.3 Slide 6

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 num1 38 name1 "Steve Jobs" Wk02.3 Slide 7

8 Assignment Revisited 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 Wk02.3 Slide 8

9 Assignment Revisited For object references, the address is copied: Before: name1 name2 "Steve Jobs" "Steve Wozniak" name2 = name1; After: name1 name2 "Steve Jobs" Wk02.3 Slide 9

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 Wk02.3 Slide 10

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 Wk02.3 Slide 11

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 Wk02.3 Slide 12

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 Wk02.3 Slide 13

14 Some methods of the String class: Wk02.3 Slide 14

15 Examples of using String class: 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 "Change is inevitable" System.out.println("Original string: \"" + phrase + "\""); System.out.println("Length of string: " + phrase.length()); "Change is inevitable, except from vending machines." } mutation1 = phrase.concat(", except from vending machines."); mutation2 = mutation1.touppercase(); mutation3 = mutation2.replace('e', 'X'); mutation4 = 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 Mutated length: 27, Length Scott of Kristjanson phrase CMPT is 125/126 now: 20 SFU Wk02.3 Slide 15

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 Wk02.3 Slide 16

17 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 = 13" 3 1 4 2 "counter = 1" concat "3" 4 concat 3 "counter = " "1" 1 2 "counter = " counter++ ++counter 1 2 3 counter = 1 counter (Initial value) = 2 counter = 3 Wk02.3 Slide 17

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 Wk02.3 Slide 18

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(); Wk02.3 Slide 19

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 Wk02.3 Slide 20

21 Some Scanner class Methods String nextline() String Int float Double next() nextint() nextfloat() nextdouble() Boolean hasnext() Wk02.3 Slide 21

22 Scanner Class Example //******************************************************************** // 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!" Wk02.3 Slide 22

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 Wk02.3 Slide 23

24 Input Tokens Example //******************************************************************** // 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: Miles Per Gallon: 40.0 2.5 Wk02.3 Slide 24

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 Wk02.3 Slide 25

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 Wk02.3 Slide 26