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.

Slides:



Advertisements
Similar presentations
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
***** SWTJC STEM ***** Chapter 3-1 cg 36 Java Class Libraries & API’s A class library is a set of classes that supports the development of programs. Java.
Expressions, Data Conversion, and Input
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 DUE right now Assignment 2 Posted – Due Feb 5 prior to class Using Classes and Objects.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 3 Using Classes and Objects. Chapter Scope Creating objects Services of the String class The Java API class library The Random and Math classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
CSC 1051 M.A. Papalaskari, Villanova University CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
CSE 1201 Object Oriented Programming Using Classes and Objects.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
SEEM Java – Basic Introduction, Classes and Objects.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Collaboration Policy Programming Tests are individual work. You may not work with others in the class.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
3-1 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.
COS 312 DAY 3 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 1 posted – Due Feb 2PM Assignment 2 Posted – Due Feb 2 PM Finish Data and Expressions.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scanner Review Java Foundations: Introduction to Programming and Data Structures.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
1 CMPT 126 Java Basics Using Classes and Objects.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Variables in Java A variable holds either
Formatting Output & Enumerated Types & Wrapper Classes
Project 1.
Using Classes and Objects
CSC 1051 – Data Structures and Algorithms I
Data Conversion & Scanner Class
Creating Objects & String Class
Chapter 3: Using Classes and Objects
Introduction to Classes and Methods
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference.
Packages & Random and Math Classes
Outline Creating Objects The String Class The Random and Math Classes
Reading Input and Scanner Class
Presentation 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

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

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

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

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

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

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

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:

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"

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

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

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

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

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:

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

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…

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 = "

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

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 ();

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

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()

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!

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

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

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

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