COMP-202 Unit 8: Basics of Using Objects

Similar documents
COMP-202 Unit 5: Basics of Using Objects

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

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

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

Classes and Objects Part 1

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Using Classes and Objects. Chapter

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

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

Full file at

Packages & Random and Math Classes

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Chapter 3: Using Classes and Objects

Using Java Classes Fall 2018 Margaret Reid-Miller

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

STUDENT LESSON A10 The String Class

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

Example: Computing prime numbers

Formatting Output & Enumerated Types & Wrapper Classes

More on variables and methods

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

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

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Conditional Programming

Midterms Save the Dates!

Text User Interfaces. Keyboard IO plus

CHAPTER 7 OBJECTS AND CLASSES

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

CHAPTER 7 OBJECTS AND CLASSES

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

Using Classes and Objects

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

COMP 202 Java in one week

Lecture Notes for CS 150 Fall 2009; Version 0.5

CS 112 Introduction to Programming

COP 3330 Final Exam Review

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination

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

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination

Creating and Using Objects

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Defining Classes and Methods

Objects and Classes -- Introduction

Computational Expression

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

First Java Program - Output to the Screen

ECE 122. Engineering Problem Solving with Java

Programming with Java

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

COMP 202. Java in one week

Chapter 4 Classes in the Java Class Libraries

Java Input/Output. 11 April 2013 OSU CSE 1

! 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

H212 Introduction to Software Systems Honors

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Computer Science 145 Midterm 1 Fall 2016

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

Basic Computation. Chapter 2

CS 211: Existing Classes in the Java Library

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

Midterms Save the Dates!

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Input. Scanner keyboard = new Scanner(System.in); String name;

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

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Java Coding 3. Over & over again!

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

A Quick and Dirty Overview of Java and. Java Programming

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

Example: Tax year 2000

Basic Computation. Chapter 2

Lab5. Wooseok Kim

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

STUDENT LESSON A5 Designing and Using Classes

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

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Full file at

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

Full file at

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2011) - All Sections Midterm Examination

CS 231 Data Structures and Algorithms, Fall 2016

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Transcription:

COMP-202 Unit 8: Basics of Using Objects CONTENTS: Concepts: Classes and Objects Creating and Using Objects Introduction to Basic Java Classes (String, Scanner, ArrayList,...)

Introduction (1) As we know, there are three possible roles for a class in Java We know that a class can be the starting point for a program Any class that defines a main() method has this role We know that a class can be a collection of related methods; such a class is sometimes called a method library The Math class from the Java Standard Class Library is perhaps the best example of a class which has such a role We know that a class can define a record type A class which has this role specifies a number of fields We can then declare variables whose type is a class which has this role, allocate records of this type, and store their addresses in memory in these variables 2

Introduction (2) Each of these records has all the fields specified by the class Objects are an extension of records Classes which define a record type can specify behaviors in addition to fields These behaviors are implemented by declaring methods in the class which defines the record type Alternatively, we can think of records as degenerate objects Full-fledged objects have attributes (implemented using fields) and behaviors, while records only have attributes 3

Introduction (3) In the programs that we have written, we have created objects When we write Scanner keyboard = new Scanner(System.in); we create a new object which belongs to class Scanner We have also requested that these objects perform certain behaviors; we do this by invoking a method on the object nextint() is a method; when we write keyboard.nextint() in a statement, we invoke the nextint() method on the Scanner object whose address in memory is stored in variable keyboard println() is also a method; when we write System.out.println(), we invoke the println() method on the PrintStream object whose address in memory is stored in variable System.out 4

Object-Oriented Programming (1) The idea behind object-oriented programming is to organize our programs as a series of objects which interact with each other by requesting that they perform certain behaviors This enables us to write code which is more maintainable than if we deal only with the methods and records we have seen so far For now, we will learn How to create and use objects which belong to classes that other people have written How to call methods on these objects Later, we will learn How to extend our own record types to turn them into full-fledged object types 5

Part 1: Basics of Classes, Objects, and Methods

Objects (1) In object-oriented programming languages like Java, objects represent individual and identifiable items or entities These items or entities can be real or conceptual They have a well-defined purpose and function in the problem domain In a computer-based system, an object may stand for itself Entities like files, network connections, windows, and menu items can be represented using objects Objects in computer-based systems may also represent realworld entities In a traffic simulation program, cars, streets, and intersections could all be represented using objects 7

Objects (2) The distinction between objects that represent themselves and those representing real-world entities is not always clear-cut Are bank accounts real-world entities or simply objects in a computer program? When an object represents a real-world entity, it is an abstraction of this entity Not everything about the real-world entity is represented by the object What is represented and what is not depends on the application or system, as well as the functionality we want them to have Objects have attributes and behavior So far, what we have seen as records were really degenerate objects which only had attributes, and no behaviors 8

Object Examples Some things that could be represented by objects: Professor Cuthbert Calculus, scientist, living in Marlinspike Hall Uncle Scrooge's bank account at Duckburg bank A network connection to server www.mcgill.ca on port 80 9

Classes: Categories of Objects Objects can be divided in categories Each such category is represented by a class The class specifies what objects that belong to that category "look" like, and how they "behave" In a general way, all objects that belong to a given class "look" similar and "behave" in a similar manner We can also think of a class as a model or a blueprint which describes the general "appearance" and "behavior" of all objects that belong to this class, and from which we can create the objects that belong to this class This is an extension of the idea that a class can define a type of record 10

Objects: Attributes The "appearance" of the objects that belong to a class is determined by the attributes defined in that class The class defines attributes that all objects that belong to this class will have However, the value of each attribute can differ from one object to the next, even if both objects belong to the same class The appearance of an object (its attributes and their values) at a given point in time is sometimes called the state of this object 11

Objects: Behavior The behavior of the objects that belong to a class is specified by the methods declared in that class; we invoke one of these methods on an object when we want the latter to act in a certain way All objects that belong to a class have the general behaviors specified by the methods defined in that class However, the exact behavior of an object when a given method is invoked on it may depend on the state of the object 12

Objects: Instances of Classes An object is an instance of a class Thus, it is an entity which belongs to the category defined by a class, and which looks and behaves according to the definition of that class Each object belongs to one class When we create an object, we must specify the class to which it belongs The process of creating an object is sometimes called instantiation 13

Physical World Analogy (1) If one were to represent human being as classes and objects, then we could define a Human class This class could define attributes and behavior which every human being has For example, every human being has a name, a gender, a date of birth, a height, a weight, eye / hair / skin colors,... Therefore, all of these could be attributes defined in our Human class Also, every human being can walk, talk, eat, and sleep, so these could be the behaviors defined in our Human class, represented as methods 14

Physical World Analogy (2) Every human being would be an object that belongs to class Human, a separate instance of our Human class Although all of us have a name, a gender, a date of birth, and so on, these might vary from one person to the next Although everyone can walk, talk, and eat, some of us perform these tasks differently from others, depending on our attributes (for example, your height and weight may affect how fast you walk) Therefore: Both the object representing Jane Doe and the object representing Joe Bleau have a weight attribute However, the value of the weight attribute of the object representing Joe Bleau may not be the same as the weight attribute of the object representing Jane Doe 15

Physical World Analogy (3) Also: Both the object representing Joe Bleau and the object representing Jane Doe can walk They both have a walk behavior because they both belong to class Human, and the Human class defines that all objects that belong to it have a walk behavior However, Jane Doe might walk faster than Joe Bleau because she is lighter than him Finally: No human being can fly, so the Human class does not define a fly behavior Therefore, trying to request that a Human object fly would not work 16

Physical World Analogy (4) On the other hand, you can still request that an object that belongs to a class which does define a fly behavior (like an object belonging to class Bird or Bat) to fly 17

Object Identity In addition to attributes and behaviors, objects also have identity Identity is the property that distinguishes an object from all others It is always possible to distinguish two objects, even if they have the same attributes Think of identical twins; even though they have the same DNA, they are different human beings An object's name or reference should not be confused with its identity 18

Objects and Abstraction We know that an abstraction hides (or ignores) details An object is abstract in that we don't really have to think about its internal details in order to use it We do not need to know how the object keeps track of its attributes internally, nor which statements are in the methods implementing its behaviors This is just like we don't really have to think about how the engines of our cars work in order to drive them Again, this enables us to write complex software without having to know how parts of it actually work We just have to know what they do when we use them 19

Part 2: Creating and Using Objects

The Account Class Let us suppose that someone has already written an Account class that we can use in a program that manages bank accounts We will use this class to illustrate how to create and use objects Note that this Account class is not included with the Java environment; you have to download it separately in order to use it Also note that it looks and behaves the way it does because the person who wrote it chose to have it look and behave this way With the proper knowledge, you could write an Account class that looks and behaves differently; we will cover this later in the course 21

The Account Class: Attributes All objects that belong to the Account class have the following attributes: An account number, which uniquely identifies the account A balance, which keeps track of the amount of money stored in the account A status, which keeps track of whether the account is open or closed 22

The Account Class: Behaviors (1) This Account class also defines the following methods for all Account objects: public Account(int number): A constructor, which creates a new Account object with the specified number, and a balance of $0 public Account(int number, double initialamount): Another constructor, which creates a new Account object with the specified number, and immediately deposits initialamount into the Account public int getnumber(): Retrieves the account number of an Account object public double getbalance(): Retrieves the balance of an Account object 23

The Account Class: Behaviors (2) public boolean isopen(): Retrieves whether the Account object is open or not; returns true if the Account is open, false if it is not public boolean deposit(double amount): Deposits the specified amount into the Account, updating its balance; returns true if the withdrawal is successful, false if it fails public boolean withdraw(double amount): Withdraws the specified amount from an Account object, updating its balance; returns true if the withdrawal is successful, false if it fails public boolean close(): Closes an Account object, so that it is no longer possible to withdraw money from it or deposit money into it; returns true if the Account is successfully closed, false if it fails to close the Account 24

The Account Class: Behaviors (3) public boolean equals(object o): Compares an Account object to another object o for equality; an Account object is equal to this other object o if this other object also belongs to the Account class, and has the same number, balance, and status public String tostring(): Produces a textual representation of an Account object suitable for display using System.out.println() 25

The Account Class: Behaviors (4) The Account class also defines behaviors which affect all existing Account objects all at once rather than one individual Account object: public static double getfee(): Retrieves the fee currently charged to an Account object when a withdrawal is performed; this fee is the same for all Account objects, and therefore can always be retrieved, regardless of whether any Account objects currently exist public static void setfee(double newfee): Sets the fee charged to an Account objects when a withdrawal is performed to newfee; this fee is the same for all Account objects, and therefore can always be set, regardless of the number any Account objects currently exist 26

Object Variables We know that a class name can be used like a type in a variable declaration to declare a reference variable Account scroogeaccount; The above statement is a variable declaration The name of the variable is scroogeaccount The type of the variable is Account However, just like with records, this variable declaration does not create any object; it merely declares a variable that can keep track of an object in memory Such a variable stores the address in memory where the object is stored, not the object itself It is like any other reference variable 27

Creating Objects (1) Creating objects and creating records are very similar operations We use the new operator to create an object, just like when we create a record The difference is that we can specify optional actual parameters between the parentheses scroogeaccount = new Account(12345); Actual parameters (if necessary) 28

Creating Objects (2) We have seen something like this before: keyboard = new Scanner(System.in); 29

Calling Constructors (1) The line scroogeaccount = new Account(12345); invokes an Account constructor A constructor is a special list of instructions that are executed when the new operator is used; its purpose is to initialize an object A class may define more than one constructor All constructors for a given class have the same name as that class They are distinguished by the number and types of inputs they accept Basically, we can overload a constructor like we can overload methods Constructor are very similar to methods, but they are technically not methods 30

Calling Constructors (2) Just like methods, constructors can be defined to take any number of parameters: one, many, or none at all However, it is the person who writes a class that decides how many parameters each constructor takes, and the types of these parameters The actual parameters passed to a constructor follow the same syntactic and semantic rules as the actual parameters passed during a call to a regular method They are expressions separated by commas The regular parameter passing mechanisms apply for each parameter type (primitive or reference) Creating an object is called instantiation, because an object is an instance of a particular class 31

Invoking Methods on Objects (1) When invoking a method on an object, we must specify a reference variable which contains the address in memory of the object on which we want to invoke the method This can be done using the. operator, as if we were accessing a record field; the syntax is the following: variablename.methodname(parameters) This does not apply when using the new operator Therefore, if we want to call the getnumber() method on the Account object that the reference variable a1 (of type Account) refers to, we write: a1.getnumber() 32

Invoking Methods on Objects (2) This is unlike what we have seen so far Up until now, we invoked most methods by specifying the name of a class in front of the. operator, not the name of a variable However, we have seen some examples of invoking a method on an object by specifying the name of a variable in front of the. operator: int value = keyboard.nextint(); boolean same = s1.equals(s2); int result = s1.compareto(s2); 33

Invoking Methods on Objects (3) The object on which the method is called is often referred to as the target of the method call In the previous example, the target of the call to the getnumber() method is the Account object whose address is stored in variable a1 Even though the target is not passed as an actual parameter to the method, it acts like one in many ways In particular, a method call can change the state of the target object For example, the deposit() method changes the value of the balance attribute of the object on which it is called Otherwise, methods called against objects work the same way as the methods we declared and called earlier 34

Invoking Methods on Objects (4) The main difference is that instead of writing the name of a class in front of the. operator, we write the name of a variable containing the address of an object Method invoked using this syntax (variable name in front of the. operator) are called instance methods Method invoked using the syntax we saw before (class name in front of the. operator) are called class methods or static methods The only methods we can invoke on an object are those defined in the class that the object belongs to If you try to invoke any other method on this object, the compiler will report an error 35

The. Operator (1) Java uses the period as membership designation For example: scroogeaccount.deposit(1000000.0); The. operator In the above example, the. indicates that we want to invoke the deposit() method on the scroogeaccount object In general, the. operator is used to indicate that we want to access a member (either a behavior or an attribute) of an object or class 36

The. Operator (2) Consider the following code fragment: Account scroogeaccount = new Account(12345); Account donaldaccount = new Account(67890); To retrieve the account number from Account object scroogeaccount, we invoke the getnumber() method on it like this: scroogeaccount.getnumber(); To retrieve the account number from Account object donaldaccount, we invoke the getnumber() method on it like this: donaldaccount.getnumber(); This works only for objects, not primitive types 37

Object Attributes In most cases, it is not possible to access the attributes of an object like we access the fields of a record (that is, using the. operator) This is because the internal details of an object are hidden In a well-designed program, only the methods declared inside a class can access the attributes of objects which belongs to that class Methods declared in all other classes MUST manipulate the object by calling public methods on it Although this appears overly restrictive at first glance, it makes the overall program easier to maintain (especially we change the internal details of the objects which belong to a class) 38

Objects and Reference Types (1) Object types are basically record types, and therefore behave like them in most respects: A variable whose type is an object type does not store the object itself; it stores the address where the object is stored in memory Declaring a variable whose type is an object type does not allocate the object itself; if it is necessary to allocate a new object, this must be done in a separate step using the new operator The assignment operator (=) evaluates the expression on the right, and copies the address it produces in the variable on the left; it does not allocate a new object Objects can be aliased; if you change the state of the object through one of its aliases, the change will be reflected by its other aliases 39

Objects and Reference Types (2) The equality (==) and inequality (!=) operator compare the addresses on each side for (in)equality, not the state of the objects stored in memory at the addresses on each side When an object is passed to a method as an actual parameter, the actual parameter and the formal parameter become aliases When your program can no longer access an object, the memory it occupies is reclaimed by the garbage collector You can assign null to any object variable Specifying a variable which contains null as the target of an instance method call will result in a NullPointerException 40

The equals() Method (1) Remember that for all reference types (including arrays, record types, and object types), the == and!= operator verify whether the variables on both sides refer to the same object To determine whether two reference variables refer to (perhaps different) objects which have the same state, we use the equals() method The equals() method returns a value of type boolean which can be used in an expression or stored in a variable Account a1 = new Account(12345); Account a2 = new Account(12345); boolean b = (a1.equals(a2)); // b gets assigned true 41

The equals() Method (2) If the two reference variables refer to the same object in memory, the equals() method will return true as well This is because an object has the same state as itself The equals() method works for all reference variables (of any object type), but exactly what it does and what it compares depends on the classes of the objects Check the documentation for details Do not use the == and!= operators to compare objects that belong to any class unless you really want to check whether two reference variables are aliases for the same object This is one of the most common mistakes 42

Using the equals() Method (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 boolean b = (a1.equals(a2)); // Line 3 Line 1: a1 12345/$0 Line 2: a1 12345/$0 a2 Line 3: a1 12345/$0 a2 b true 43

Using the equals() Method (2) Account a1 = new Account(12345); // Line 1 Account a2 = new Account(12345); // Line 2 boolean b = (a1.equals(a2)); // Line 3 Line 1: a1 12345/$0 Line 2: a1 12345/$0 12345/$0 a2 Line 3: a1 12345/$0 12345/$0 a2 b true 44

Class / Static Methods In Java, many methods require an object in order to work That is, they require that an object be specified when they are invoked, and the method is invoked on that object For example, it makes no sense to try to invoke the deposit() method without specifying which Account object we want to deposit money into However, there are methods which do not work on an object, and thus do not require an object to be specified when they are invoked That is, we do not need to declare a reference variable and create an object before calling these methods The methods we wrote earlier in the course are like this; such methods are class methods or static methods 45

Invoking Class / Static Methods As we know, to invoke a class method, we use the following syntax: classname.method(parameters); This syntax works only for class methods Therefore, if we want to retrieve the current withdrawal fee, we could do so by calling the getfee() method like this: Account.getFee(); The withdrawal fee exists regardless of the number of Account objects which exist at a given point in the program, and therefore can always be retrieved or changed We do not need to declare a reference variable of type Account and assign it the address of an Account object in order to invoke the getfee() method 46

Class / Static Constants In addition to class methods, some classes define class constants To use a class constant, we use the following syntax class.constant The Account class defines one constant, which represents the ID number of the bank in which Accounts are opened: BANK_ID_NUMBER Therefore, if we wish to use this constant in an expression, we would write Account.BANK_ID_NUMBER 47

The tostring() Method (1) You can display the object whose address is stored in a reference variable just like you can display the value of a primitive variable The following code fragment will display the Account object whose address is stored in variable scroogeaccount: System.out.println("Scrooge's bank account: " + scroogeaccount); In the above line, the tostring() method is invoked automatically on the Account object whose address is stored in variable scroogeaccount The tostring() method produces a text representation of the target account 48

The tostring() Method (2) You can also call the tostring() method on an object explicitly to generate a text representation of the object: String text = scroogeaccount.tostring(); Like the equals() method, the tostring() method works for all reference variables (of any object type), but exactly what it does and what it displays depends on the class of the target object Check the documentation of each class for details 49

Documentation Most classes come with documentation which describes the constructors, methods, and class constants defined in the class 50

Reading Documentation (1) The class constants, constructors, and methods are listed in separate sections Reading field descriptions: A field listed as static final is a class constant The type listed in the left column is the type of the constant Reading constructor and method descriptions: The left column specifies the method's return type (constructors do not have return values or return types) and modifiers If the method / constructor is listed as protected, you cannot call it; circumstances in which you could call it are beyond the scope of this course 51

Reading Documentation (2) If the method is listed as static, it is a class method (constructors cannot be static); if the method is not listed as static, it is an instance method The right column lists the name of the method or constructor, as well as the parameters it accepts; for example: Account(int number, double initialamount) is a constructor that accepts as parameters a value of type int and one of type double (in that order) The method description specifies what the method does, and what each parameter (as well as the return value) represents 52

Classes and Objects: Exercise (1) Familiarize yourself with the Bank and Account classes by reading the relevant documentation Write a program which consists of one class called BankManager. This class should define a main() method which does the following: Displays a menu to the screen with the following options: create an account, view an account, deposit, withdraw, close an account, change the withdrawal fee, and exit Reads the option chosen by the user 53

Classes and Objects: Exercise (2) Takes the appropriate action depending on the option chosen by the user; for example, if the user chooses the withdrawal option, it should prompt the user for an account number and an amount, read these values from the keyboard, and deposit the amount in the appropriate account Repeat the above steps as long as the user does not choose the exit option The program must display appropriate messages depending on the success or failure of the user's actions Use a Bank object to keep track of the various Account objects created by the user 54

Part 3: The String Class and String Objects

Strings in Java (1) In Java, every character string is an object which belongs to the String class The String class is defined in the Java Standard Class Library which is part of all Java development environments This class defines all the methods that can be called using String objects as targets Because Strings are so common, the Java programming language provides us with some syntactic sugar that allows us to use Strings almost in the same way we use primitive types 56

Strings in Java (2) In particular, we do not have to use the new operator to create a String object; we can simply assign a String literal to a String variable String name; name = "Cuthbert Calculus"; This is special syntax that works only for String objects 57

Strings in Java (3) Despite this, the String type is still a reference type Strings are objects, and therefore, they are stored in memory like all other objects That is, a variable of type String contains the address in memory where the String object is located, not the String object itself This implies that the = operator makes two String variables become aliases for the same String object It also implies that the == and!= operators check whether two String variables are aliases (or not) for the same String object This is why you should always use the equals() method to see if two String objects are equal, unless you are really sure of what you are doing; not doing this is a common source of errors 58

String Methods (1) The String class defines several methods which you may use to manipulate String objects. Here are some of them: String(String original): (Constructor) Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created String is a copy of the argument String. char charat(int index): Returns the char value at the specified index. int compareto(string anotherstring): Compares two strings lexicographically. boolean equals(object anobject): Compares this String to the specified object. 59

String Methods (2) boolean equalsignorecase(string anotherstring): Compares this String to another String, ignoring case considerations. int length(): Returns the length of this String. String replace (char oldchar, char newchar): Returns a new String resulting from replacing all occurrences of oldchar in this String with newchar. String substring(int beginindex, int endindex): Returns a new String that is a substring of this String. String tolowercase(): Converts all of the characters in this String to lower case using the rules of the default locale. String touppercase(): Converts all of the characters in this String to upper case using the rules of the default locale. 60

Immutability String objects are immutable This means that once a String object is created, its state cannot change None of the String methods can change the state of a String object, nor can any other method defined in any other class This has to do with the way the String class is implemented Methods that seem to change a String object in fact create a new String object from the original target String However, you can always change the reference stored in a String variable to make it refer to a different String object (unless the variable is final) Note that objects belonging to other classes can be immutable as well (this depends on how the class is implemented) 61

String Indexing (1) Just like with arrays, the i th character in a String has index i - 1 In other words: If you want to recover the first character of String variable s, you must use s.charat(0), not s.charat(1) More generally, if you want to recover the i th character of String variable s, you must use s.charat(i-1), not s.charat(i) Consequently, the last character of a String variable s has index s.length() 1 Example: String s1 = "Hello world!" char c = s1.charat(4); // c contains the character 'o', not 'l' 62

String Indexing (2) If you attempting to access the character in a String located at an invalid index (either negative, or greater than or equal to the number of characters in the String), your program will crash: String s = "hello"; char c = s.charat(5); // String s contains 5 characters, so // the valid indices for s are 0-4 // inclusive: crash! When this occurs, the error message will mention that the program threw a StringIndexOutOfBoundsException The error message should also mention which line in your program caused the latter to crash 63

IndexOutOfBoundsDemo.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class IndexOutOfBoundsDemo { public static void main(string[] args) { String s; } } s = "hello"; System.out.println("Attempting to retrieve the " + "character at position " + s.length() + " of " + "String " + s); System.out.println("The character at position " + s.length() + " of String " + s + ": " + s.charat(s.length())); 64

Reading Exception Output The program's output: Attempting to retrieve the character at position 5 of String hello Exception in thread "main" java.lang. StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.string.charat(string.java:687) at IndexOutOfBoundsDemo.main(IndexOutOfBoundsDemo.java:10) More details on the problem Index we tried to access and caused the crash 65

Array Length and String Length When we retrieve the length of an array, we access its length field Because we are accessing a field, we MUST NOT write parentheses after the word length We therefore write myarray.length, where myarray is a variable whose type is an array type However, when we retrieve the length of a String, we call its length() method Because we are calling a method, we MUST write parentheses after the word length We therefore write mystring.length(), where mystring is a variable of type String 66

ObfuscatedHaiku.java public class ObfuscatedHaiku { public static void main(string args[]) { String s1 = new String("\t Windows Vista crashed."); String s2 = "\t Windows Vista crashed."; String today = "\t Caturday \t"; boolean answer; answer = s1.equals(s2) && s1!= s2; today = today.substring(2, 10); today = today.replace('c', 'S'); if (answer && today.equals("saturday") ) { System.out.println(s1 + "\n\t I am the" + " Blue Screen of Death."); System.out.println("\t No one hears your screams."); } } } What is the value of answer? What is today? Will we see a haiku? 67

Part 4: The Java Standard Library 68

The Java Standard Class Library As we know, there is a Java standard class library that is part of any Java development environment, which provides a number of useful classes that we can use to write programs These classes are not part of the Java language per se, but we rely on them heavily The System class, the Scanner class, and the String class are part of the Java standard class library 69

Packages The classes of the Java standard class library are organized into packages Some of the packages in the Java standard class library are: Package java.lang java.util java.io java.awt javax.swing Purpose General support (contains String and System) Utilities Input and output facilities Graphical user interfaces (old style) Graphical user interfaces (new style) java.net Networking 70

The import Declaration When you want to use a class from a package, you could use its fully qualified name: java.util.scanner keyboard = new java.util.scanner(system.in); Or you can import the class, then just use the class name: import java.util.scanner; // Class and method declarations... Scanner keyboard = new Scanner(System.in); To import all classes in a particular package, you can use the * wildcard character: import java.util.*; An import declaration must always be placed before the class declaration 71

Implicit import Declarations All classes of the java.lang package are automatically imported into all programs Classes String and System are part of the java.lang package That's why we didn't have to explicitly import the System or String classes in earlier programs 72

The Scanner Class (1) The Scanner class is part of the Java standard class library It is part of the java.util package; therefore, you must import it in the classes that you write that use it, or use the fully qualified name when declaring Scanner variables It provides several methods for converting the bytes read from various sources (keyboard, files) into primitive values and Strings A Scanner object assumes that white space (delimiters) separates elements of the input (tokens) Delimiters may be different when reading different types of data 73

The Scanner Class (2) Watch out, especially when trying to read a String with nextline() immediately after reading a numeric value from the keyboard Constructors provided by the Scanner class take as input an objects representing the source we want to read from; so far, we have only read from System.in, an InputStream object representing the keyboard Later in the course, we will see how to create Scanner objects which read from a file on disk instead of the keyboard 74

Scanner Methods (1) Some methods defined in class Scanner: public Scanner(InputStream source): (Constructor) Constructs a new Scanner that produces values scanned from the specified input stream. public Scanner(File source): (Constructor) Constructs a new Scanner that produces values scanned from the specified file. public Scanner(String source): (Constructor) Constructs a new Scanner that produces values scanned from the specified string. public String next(): Finds and returns the next complete token from this Scanner. public String nextline(): Advances this Scanner past the current line and returns the input that was skipped. 75

Scanner Methods (2) public double nextdouble(): Scans the next token of the input as a double. public int nextint(): Scans the next token of the input as an int. public long nextlong(): Scans the next token of the input as a long. public String nextboolean(): Scans the next token of the input into a boolean value and returns that value. public boolean hasnext(): Returns true if this Scanner has another token in its input. public boolean hasnextline(): Returns true if there is another line in the input of this Scanner. 76

Scanner / Strings: Exercise Complete the main() method of the PrintNames class by adding code that does the following: Prompts the user to enter his / her first name and reads it from the keyboard Prompts the user to enter his / her last name and reads it from the keyboard Displays the full name of the user on one line, with the first name followed by the last name Performs the above steps until the user enters an empty line when prompted to enter his / her first name Can you think of more than one way to check whether the user entered an empty line? 77

PrintNames.java import java.util.scanner; public class PrintNames { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); } } // Add your code here 78

(Pseudo-)Random Numbers (1) Computers are deterministic This means that whenever a program in a given state receives a given input, the output will always be the same Because of this, generating truly random numbers with a computer is very hard, if not impossible Therefore, we have to settle for generating pseudo-random numbers Pseudo-random number generators perform a series of complicated calculations, based on an initial seed value, and produce some values One of these values is the random number returned, the other is stored and used to generate the next random number when one is needed 79

(Pseudo-)Random Numbers (2) Numbers generated using pseudo-random number generators appear to be randomly selected They pass statistical randomness tests However, because of the deterministic nature of computers, whenever you use a given algorithm to generate pseudo-random numbers and initialize it with a fixed seed, you will generate the same number sequence 80

The Random Class (1) The Random class is part of the java.util package It provides methods that generate pseudo-random numbers: public Random(): (Constructor) Creates a new pseudo-random number generator, with an initial seed very likely to be distinct from any other Random object initialized by another invocation of this constructor. public Random(long seed): (Constructor) Creates a new pseudorandom number generator with the specified seed. public double nextdouble(): Returns a random number between 0.0 (inclusive) and 1.0 (exclusive). public int nextint(): Returns a random number that ranges over all possible int values (positive and negative). 81

The Random Class (2) public int nextint(int n): Returns a random number in the range 0 to n - 1 82

RandomNumber.java import java.util.random; public class RandomNumber { public static void main(string args[]) { Random generator = new Random(); int i; float f; } } i = generator.nextint(10); // 0-9 f = generator.nextfloat(); // 0.0-1.0 System.out.println("The randomly generated integer is: " + i); System.out.println("The randomly generated real number is: " + f); 83

RandomSequence.java (1 / 2) import java.util.random; import java.util.scanner; public class RandomSequence { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in);; Random generator; final int MAX = 100; long seed; int number; System.out.print("Enter a seed : "); seed = keyboard.nextlong(); System.out.print("How many values do you want to " + "generate: "); number = keyboard.nextint(); System.out.println(); // Continued on next slide 84

RandomSequence.java (2 / 2) } } // Continued from previous slide System.out.print("Here are " + number + " pseudo-random " + "numbers from 0 - " + (MAX - 1) + ": "); generator = new Random(seed); for (int i = 0; i < number; i++) { System.out.print(generator.nextInt(MAX) + " "); } System.out.println(); What happens: when you run this program twice with the same seed? when you run this program twice with different seeds? 85

Formatting Output (1) The DecimalFormat class can be used to format a floating point value in generic ways It is defined in package java.text For example, you can specify that the number is to be printed to three decimal places First you have to create an object of the class DecimalFormat For that, you use the constructor of the DecimalFormat class The constructor takes a String that represents a pattern (for example, indicating three decimal places) Patterns can be quite complex 86

Formatting Output (2) You can call the format() method on a DecimalFormat object; it takes as input a floating point number and returns a String representation of that number in the appropriate format 87

Formatting Output: Exercise 1 Make the following modifications to the SimpleCircle class you completed in an earlier exercise: Change its name to FormattedCircle Change the code displaying the results so that the program displays the results with a maximum of 3 digits after the decimal point: the appropriate pattern is "0.###" Once it works properly, experiment by replacing the above pattern with the following: "0.#####". How does the output change? 88

More on Formatting Output (1) The NumberFormat class has class methods that return certain formatter objects: getcurrencyinstance(): Returns a formatter object that formats values as currencies getpercentinstance(): Returns a formatter object that formats values as percentages Each formatter object has a method called format(); calling this method with a numeric value as parameter returns a String representation of the value in the appropriate format Class NumberFormat is also part of the java.text package 89

More on Formatting Output (2) Example: NumberFormat formatter = NumberFormat.getCurrencyInstance(); String s = formatter.format(100); // s is now "$100.00" The formatters returned by the getcurrencyinstance() and getpercentinstance() methods format their input in a way which depends on the locale of the computer on which the program runs The locale consists of all the location / country / language dependent settings Therefore, two computers with two different locales running the same program may display differently-formatted output 90

Formatting Output: Exercise 2 Complete the main() method of the Taxes class by adding code that does the following: Computes the GST and the PST to be paid on the price entered by the user; note that the PST is calculated on the sum of the price before taxes and the GST to be paid on that price Computes the total price to be paid Displays the GST amount, the PST amount, and the total with appropriate messages for each value; all of these values should be formatted as currencies by using an appropriate formatter object 91

Taxes.java import java.util.scanner; public class Taxes { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); final double GST = 0.05; final double PST = 0.075; double price; } } System.out.print("Enter the price of the item: "); price = keyboard.nextdouble(); // Add your code here 92

Wrapper Classes Remember that there are two categories of data in Java: primitive data and objects We use wrapper classes to manage primitive data as objects Each wrapper class represents a particular primitive type Integer everest = new Integer(8850); We have just "wrapped" the primitive integer value 8850 into an object referenced by the everest variable This is useful to store primitive data in container classes We will cover container classes when we cover arrays All wrapper classes are part of the java.lang package: Byte, Short, Integer, Long, Float, Double, Character, Boolean 93

Integer Methods (1) Some methods defined in class Integer: Integer(value): (Constructor) Constructs a newly allocated Integer object that represents the specified int value. byte bytevalue(): Returns the value of this Integer as a byte. double doublevalue(): Returns the value of this Integer as a double. float floatvalue(): Returns the value of this Integer as a float. int intvalue(): Returns the value of this Integer as an int. long longvalue(): Returns the value of this Integer as a long. static int parseint(string s): Parses the String argument as a signed decimal integer 94

Integer Methods (2) static String tobinarystring(int i): Returns a String representation of the integer argument as an unsigned integer in base 2. Example: String s = "500"; int number = Integer.parseInt(s); // number now contains the int value 500 95

Java Library Reference All the details of all classes defined in the Java library can be found here: Java 6: http://java.sun.com/javase/6/docs/api/ Java 5: http://java.sun.com/j2se/1.5.0/docs/api/ Do not hesitate to consult this reference to do your assignments 96

Part 5: Exercises 97

Exercises (1) 1) Write a Java class called KillWhiteSpace, which defines a main() method that asks the user to enter a String s, and displays a new String consisting of all the characters in s, but with the leading and trailing white space removed. In addition, every sequence of spaces within the String is reduced to one space only. You MUST NOT use any methods defined in the String class other than charat() and length(). 98

Exercises (2) 2) Write a Java class called OccursAnywhere, which defines a main() method that asks the user to enter two Strings, superstring and substring, and displays whether or not substring occurs anywhere in superstring. You MUST NOT use any method defined in the String class other than chartat() and length(). 99