COMP-202 Unit 5: Basics of Using Objects

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

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

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

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

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

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

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

Classes and Objects Part 1

Packages & Random and Math Classes

Example: Computing prime numbers

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Using Java Classes Fall 2018 Margaret Reid-Miller

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Full file at

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

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

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

COMP 202 Java in one week

2 rd class Department of Programming. OOP with Java Programming

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

Creating and Using Objects

COMP 202. Java in one week

First Java Program - Output to the Screen

Objects and Classes -- Introduction

Chapter 2: Data and Expressions

"Hello" " This " + "is String " + "concatenation"

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

St. Edmund Preparatory High School Brooklyn, NY

Chapter 2: Data and Expressions

Chapter. Let's explore some other fundamental programming concepts

Defining Classes and Methods

Midterms Save the Dates!

Primitive vs Reference

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

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

STUDENT LESSON A10 The String Class

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

COMP 202 Java in one week

CMPT 125: Lecture 3 Data and Expressions

Lecture Notes for CS 150 Fall 2009; Version 0.5

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

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

Computer Science is...

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

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

Last Class. More on loops break continue A bit on arrays

Computer Science is...

AP Computer Science A

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

Table of Contents Date(s) Title/Topic Page #s. Abstraction

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

Lecture Set 2: Starting Java

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

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

Lecture Set 2: Starting Java

2: Basics of Java Programming

Elementary Programming

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

COMP-202 More Complex OOP

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

Basic Computation. Chapter 2

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

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

Midterms Save the Dates!

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

BM214E Object Oriented Programming Lecture 8

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper

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

Programming with Java

JAVA: A Primer. By: Amrita Rajagopal

Last Class. While loops Infinite loops Loop counters Iterations

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

! 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

CS112 Lecture: Primitive Types, Operators, Strings

Basic Computation. Chapter 2

Notes from the Boards Set BN19 Page

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

Math Modeling in Java: An S-I Compartment Model

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

STUDENT LESSON A5 Designing and Using Classes

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

CS 231 Data Structures and Algorithms, Fall 2016

Pace University. Fundamental Concepts of CS121 1

6.001 Notes: Section 8.1

COMP-202 Unit 4: Programming with Iterations

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Transcription:

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

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 So far, all the classes that we have written have had this role, and only this role However, a class can also have two other roles It can be a collection of related methods, which are lists of statements that have a name, that perform a task, and that can be executed by invoking them It can define a category of objects, and specify what the objects that belong to this category look like and how they behave COMP-202 - Basics of Using Objects 2

Introduction (2) In the classes that we write, we can use the classes that have one (or both) of these two other roles We can create and use objects that belong to these classes We can call or invoke the methods defined in these classes by writing a single statement; when we do this, the statements that the method consists of are executed COMP-202 - Basics of Using Objects 3

Introduction (3) We have already created objects and invoked methods in the programs that we have written When we write Scanner keyboard = new Scanner(System.in); we create a new object which belongs to class Scanner nextint() is a method; when we write keyboard.nextint() in a statement, we invoke the nextint() method on the Scanner object that the variable keyboard keeps track of, and the statements that this method consists of are executed println() is also a method; when we write System.out.println(), we invoke the println() method on the PrintStream object that the variable System.out keeps track of, and the statements that it consists of are executed COMP-202 - Basics of Using Objects 4

Using Objects and Methods (1) Classes, objects, and methods are powerful tools They enable us to have the programs we write use the lists of statements someone else has written This has the potential to greatly reduce our workload; someone else has already written parts of the program for us Learning how to use classes, objects, and methods will enable us to write larger, more interesting programs For now, we will learn How to create and use objects which belong to classes that other people have written How to call methods that other people have written COMP-202 - Basics of Using Objects 5

Using Objects and Methods (2) Later, we will learn How to write our own classes which define our own categories of objects How to write our own methods that we (or someone else) can invoke in our programs COMP-202 - Basics of Using Objects 6

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 COMP-202 - Basics of Using Objects 8

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 COMP-202 - Basics of Using Objects 9

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 COMP-202 - Basics of Using Objects 10

Java Program Structure Revisited As we have seen before, in the Java programming language: A program consists of one or more classes All our programs so far have only consisted of one class we wrote ourselves, with some help from a few classes provided by the Java environment (Scanner, System, String, and PrintStream, in particular) COMP-202 - Basics of Using Objects 11

Classes: Categories of Objects A class can also define a category of objects It 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 COMP-202 - Basics of Using Objects 12

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 COMP-202 - Basics of Using Objects 13

Objects: Behavior The behavior of the objects that belong to a class is specified by the methods defined 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 COMP-202 - Basics of Using Objects 14

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 COMP-202 - Basics of Using Objects 15

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 COMP-202 - Basics of Using Objects 16

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 COMP-202 - Basics of Using Objects 17

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 COMP-202 - Basics of Using Objects 18

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 COMP-202 - Basics of Using Objects 19

Side Note: Abstraction 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 Just like we don't really have to think about how the engines of our cars work in order to drive them We do not have to know how a method works in order to invoke it We need to know what it does and what it needs in order to do it, but not how it does it Therefore, we can 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 COMP-202 - Basics of Using Objects 20

Libraries (1) Libraries are sets of pre-written, already-compiled code fragments that you can use in your program Libraries are like sets of lemmas in mathematics: We use lemmas to help us prove theorems; we can assume that the lemma is true without having to prove it Likewise, we use libraries to help us write programs; we can assume that the library does what its documentation tells us it will do without having to write code ourselves to do it Libraries are useful because you do not need to write code that does what the library does, someone else has done this for you COMP-202 - Basics of Using Objects 21

Libraries (2) Some libraries are included with the compiler you use; you can obtain other libraries from the Web Some libraries are free (as in "free speech", as in "free food", or both), others are not COMP-202 - Basics of Using Objects 22

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 COMP-202 - Basics of Using Objects 24

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 COMP-202 - Basics of Using Objects 25

The Account Class: Behaviors (1) This Account class also defines the following methods for all Account objects: Account(int number): A constructor, which creates a new Account object with the specified number, and a balance of $0 Account(int number, double initialamount): Another constructor, which creates a new Account object with the specified number, and immediately deposits initialamount into the Account int getnumber(): Retrieves the account number of an Account object double getbalance(): Retrieves the balance of an Account object boolean isopen(): Retrieves whether the Account object is open or not; returns true if the Account is open, false if it is not COMP-202 - Basics of Using Objects 26

The Account Class: Behaviors (2) 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 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 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 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 COMP-202 - Basics of Using Objects 27

The Account Class: Behaviors (3) String tostring(): Produces a textual representation of an Account object suitable for display using System.out.println() COMP-202 - Basics of Using Objects 28

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: 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 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 COMP-202 - Basics of Using Objects 29

Reference Types We know that there are two broad kinds of types in Java: primitive types and reference types We have already covered primitive types Reference types are closely related to classes and objects Each class which defines a category of objects also defines a reference type We can declare variables whose types are reference types, just like we declare variables whose types are primitive types COMP-202 - Basics of Using Objects 30

Reference Variables (1) A class name can be used like a type in a variable declaration to declare a reference variable; that is, a variable whose type is a reference type Account scroogeaccount; The above statement is a variable declaration The name of the variable is scroogeaccount The type of the variable is Account However, this variable declaration does not create any object; it merely declares a variable that can keep track of an object in memory COMP-202 - Basics of Using Objects 31

Primitive vs. Reference Types (1) When declaring a variable, memory cells are allocated whether the type of the variable is a primitive type or a reference type What differs is the nature of what will be stored in those cells The declaration int number; creates a variable that holds a value of type int The int value is stored directly in the memory cells that are allocated when the variable number is declared COMP-202 - Basics of Using Objects 32

Primitive vs. Reference Types (2) On the other hand, the declaration Account scroogeaccount; creates a reference variable No object is created The object will not be stored in the memory cells that are allocated when the variable scroogeaccount is declared Instead, what will be stored in those cells is the reference to the object; the location, or address, in memory where the object is stored once it is created We have seen something like this before: Scanner keyboard; Initially, variables of both kinds do not contain any data COMP-202 - Basics of Using Objects 33

Creating Objects (1) Declaring a reference variable is a separate operation from creating the object whose address in memory will be stored in that reference variables We use the new operator to create an object: scroogeaccount = new Account(12345); Constructor invocation: same name as the class We have also seen something like this before: Inputs to constructor (if necessary) keyboard = new Scanner(System.in); COMP-202 - Basics of Using Objects 34

Creating Objects (2) 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 The object will be contained in somewhere in memory, and the reference variable (scroogeaccount) will contain its location in memory (or its address) COMP-202 - Basics of Using Objects 35

Creating Objects (3) Constructors can be defined to take any number of inputs (also called parameters or arguments): 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 Creating an object is called instantiation, because an object is an instance of a particular class COMP-202 - Basics of Using Objects 36

Reference Types: Initialization The assignment number = 42; writes the value 42 into the memory cells allocated to variable number On the other hand, when the assignment scroogeaccount = new Account(12345); is executed, the following happens: A new Account object is created; it uses some memory cells The variable scroogeaccount gets assigned the address of the memory cells that contain the Account object We say that the contents of the reference variable is a reference or a pointer to the real object COMP-202 - Basics of Using Objects 37

Primitive Types: Assignment Consider the following code fragment: int i1, i2 = 8; i1 = 6; i2 = i1; When the last line of the above fragment is executed, the contents of variable i1 is copied into i2 Because the type of these variables is a primitive type, the respective contents of these variables are their actual values Thus, the value of i1 is copied into i2 If the value of i2 is modified afterwards, the value of i1 stays the same COMP-202 - Basics of Using Objects 38

Primitive Types In Memory int i1, i2 = 8; // Line 1 i1 = 6; // Line 2 i2 = i1; // Line 3 Line 1: i1 i2 8 Line 2: i1 6 i2 8 Line 3: i1 6 i2 6 COMP-202 - Basics of Using Objects 39

Reference Types: Assignment Now, consider the following code fragment: Account a1, a2 = new Account(12345); a1 = new Account(67890); a1 = a2; When the last line of the above fragment is executed, the contents of variable a2 is copied into variable a1 However, because the type of these variables is a reference type, the respective contents of these variables are the addresses of objects in memory, not the objects themselves Thus, the address stored in a2 is copied into a1 There is still only one object involved here, but its address in memory is stored in two different variables COMP-202 - Basics of Using Objects 40

Reference Types In Memory Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 1: a1 12345/$0 a2 Line 2: a1 67890/$0 12345/$0 a2 Line 3: a1 67890/$0 12345/$0 a2 COMP-202 - Basics of Using Objects 41

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; the syntax is the following: variable.method(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() COMP-202 - Basics of Using Objects 42

Invoking Methods on Objects (2) 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 COMP-202 - Basics of Using Objects 43

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 COMP-202 - Basics of Using Objects 44

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 COMP-202 - Basics of Using Objects 45

Invoking Methods in General (1) Many methods return values when invoked For example, when invoked on an Account object, the getnumber() method returns a value that has type int, the getbalance() method returns a value of type double,... These are called return values; the type of the value returned by a method is called its return type Return values can be assigned to a variable of an appropriate type Account scroogeaccount = new Account(12345); int number = scroogeaccount.getnumber(); // getnumber() returns an int // This int is assigned to int variable // number COMP-202 - Basics of Using Objects 46

Invoking Methods in General (2) Return values can also be used in expressions: Account scrooge1 = new Account(12345); Account scrooge2 = new Account(67890); double totalmoney = scrooge1.getbalance() + scrooge2.getbalance(); Many methods require parameters / arguments: The behavior of the method depends on the input values For example, the deposit() method needs one parameter: the amount of money to be deposited in the account A class may define multiple methods with the same name: each of the different versions of this method may take different numbers of parameters, and these parameters may be of different types COMP-202 - Basics of Using Objects 47

Invoking Methods in General (3) Any expression that can be used on the right side of an assignment statement can be passed as a parameter to a method, as long as the type of the expression is assignment-convertible to the parameter type the method expects When an expression is passed as a parameter to a method, the expression is evaluated first, and its value is passed to the method: int dollars = 1000000; Account scroogeaccount = new Account(12345); scroogeaccount.deposit(3 * dollars); // OK! // scroogeaccount now contains $3000000 COMP-202 - Basics of Using Objects 48

Invoking Methods in General (4) The person who writes a class decides: which methods will be defined in this class what each method will be called how many parameters each method will accept what the types of these parameters will be for each method the type of the value that each method will return 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 COMP-202 - Basics of Using Objects 49

Aliases (1) When the address in memory of one object is stored in two or more different variables, we say that the variables are aliases We need to be careful when working with aliases Aliasing has side-effects that we need to be aware of Because the variables contain the address in memory of the same object, the result of invoking a method on the object using one of its aliases will be reflected through the other aliases In particular, if you invoke a method which changes the state of the object on one of the aliases, the other aliases will reflect the change COMP-202 - Basics of Using Objects 50

Aliases (2) To "de-alias" the variables, we simply need to store the address of a different object in one of them by using an assignment statement Note that aliasing is only a property of reference types; it is not a property of primitive types COMP-202 - Basics of Using Objects 51

Alias Example Consider the following code fragment: Account a1 = new Account(12345); Account a2 = a1; a1.deposit(100.0); double balance = a2.getbalance(); What will be the value of variable balance after the last line in the above fragment is executed? The answer is: 100.0 (?!?) Because a1 and a2 are aliases for the same object, any change to the object via one of its aliases will be reflected through the other alias COMP-202 - Basics of Using Objects 52

Aliases in Memory (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 a1.deposit(100.0); // Line 3 double balance = a2.getbalance(); // Line 4 Line 1: a1 12345/$0 Line 2: a1 12345/$0 a2 COMP-202 - Basics of Using Objects 53

Aliases in Memory (2) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 a1.deposit(100.0); // Line 3 double balance = a2.getbalance(); // Line 4 Line 3: a1 12345/$100 a2 Line 4: a1 12345/$100 a2 balance 100.0 COMP-202 - Basics of Using Objects 54

Comparing Objects Among the comparison operators, only == and!= are defined for reference types If you try to compare two reference variables using <, <=, >, or >=, the compiler will report an error Moreover, when used to compare reference variables, the == and!= operators check whether the two reference variables refer to the same object in memory In other words, for reference variables, the == and!= operators check whether the addresses stored in them are the same In yet other words, the == and!= operators check whether two reference variables are aliases for the same object But two different objects, stored at different addresses, can have the same state COMP-202 - Basics of Using Objects 55

Comparing Objects Using == (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 boolean b = (a1 == a2); // Line 3 Line 1: a1 12345/$0 Line 2: a1 12345/$0 a2 Line 3: a1 12345/$0 a2 b true COMP-202 - Basics of Using Objects 56

Comparing Objects Using == (2) Account a1 = new Account(12345); // Line 1 Account a2 = new Account(12345); // Line 2 boolean b = (a1 == 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 false COMP-202 - Basics of Using Objects 57

The equals() Method (1) 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 COMP-202 - Basics of Using Objects 58

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 COMP-202 - Basics of Using Objects 59

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 COMP-202 - Basics of Using Objects 60

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 COMP-202 - Basics of Using Objects 61

Class / Static Methods In Java, most 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 These methods are called class methods or static methods COMP-202 - Basics of Using Objects 62

Invoking Class / Static Methods To invoke a class method, we use the following syntax: class.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 COMP-202 - Basics of Using Objects 63

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 COMP-202 - Basics of Using Objects 64

The null Literal Value Sometimes, we want a reference variable to contain a special value to indicate that the variable intentionally does not contain the address in memory of a valid object The literal value null can be used for this purpose Like the boolean literals true and false, null is not technically a reserved word, but you cannot use it for any purpose other than as a literal value for reference variables A reference variable containing the value null is sometimes said to "point nowhere" In memory diagrams, null is often represented with a ground symbol COMP-202 - Basics of Using Objects 65

Using null One can assign null to a reference variable like one assigns an int literal like 42 to a variable of type int Account a1; a1 = null; One can check whether or not a reference variable contains the value null like one checks whether or not a variable of type int contains any value represented by an int literal like 42 if (a1 == null) { // do something } else { // do something else } COMP-202 - Basics of Using Objects 66

null-related Caveats The address stored in a reference variable is always either the address in memory of a valid object, or null In Java, you cannot store an arbitrary memory address in a reference variable, nor manipulate memory addresses directly If you attempt to call a method using a reference variable which contains null, your program will crash: Account a1 = null; a1.deposit(100.0); // a1 contains null: crash! When this occurs, the error message will mention that the program threw a NullPointerException The error message should also mention which line in your program caused the latter to crash COMP-202 - Basics of Using Objects 67

NullPointerDemo.java 1 public class NullPointerDemo { 2 public static void main(string[] args) { 3 Account a = null; 4 5 System.out.println("Attempting to retrieve the account " 6 + "number of a null Account..."); 7 System.out.println("The number of this account is: " + 8 a.getnumber()); 9 } 10 } What will happen if we run this program? COMP-202 - Basics of Using Objects 68

Reading Exception Output (1) The program's output: Attempting to retrieve the account number of a null Account... Exception in thread "main" java.lang.nullpointerexception ` at NullPointerDemo.main(NullPointerDemo.java:7) Method where the problem occurred File where the problem occurred Line number where the problem occurred Nature of the problem COMP-202 - Basics of Using Objects 69

Garbage Collection When there are no more reference variables containing the address of an object, the object can no longer be accessed by the program It is useless, and therefore called garbage Java performs automatic garbage collection periodically When garbage collection occurs, all the memory allocated to store garbage objects is made available so it be allocated to store new objects In other languages, the programmer has the responsibility for performing garbage collection Always ensure you do not lose the last reference to an object you still need COMP-202 - Basics of Using Objects 70

Garbage Collection in Memory (1) Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 1: a1 12345/$0 a2 Line 2: a1 67890/$0 12345/$0 a2 COMP-202 - Basics of Using Objects 71

Garbage Collection in Memory (2) Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 3: a1 67890/$0 12345/$0 a2 Garbage After Garbage Collection: a1 67890/$0 a2 COMP-202 - Basics of Using Objects 72

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 COMP-202 - Basics of Using Objects 73

The tostring() Method (2) 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 COMP-202 - Basics of Using Objects 74

Documentation Most classes come with documentation which describes the constructors, methods, and class constants defined in the class COMP-202 - Basics of Using Objects 75

Reading Documentation (1) The class constants (which are fields, but not all fields are 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 COMP-202 - Basics of Using Objects 76

Reading Documentation (2) If the method is listed as static, it is a class method (constructors cannot be static) If the return type of a method is listed as void, that means the method does not return values 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 parameter names are not important (for now); what matters is the types of the parameters, and their order The method description specifies what the method does, and what each parameter (as well as the return value) represents COMP-202 - Basics of Using Objects 77

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 COMP-202 - Basics of Using Objects 78

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 COMP-202 - Basics of Using Objects 79

Part 3: The String Class and String Objects

Strings vs. Characters (1) Characters are a single letter or symbol: char c1 = 'a'; char c2 = '%'; Strings are series of concatenated characters: String s = "Cuthbert Calculus"; Concatenation means that a block of one or more characters is appended to the end of another block of one or more characters: The concatenation of "a" and "b" is "ab"; likewise, the concatenation of "ab" and "cd" is "abcd" COMP-202 - Basics of Using Objects 81

Strings vs. Characters (2) char is a built-in, primitive type String is a reference type and a class defined in the class library that comes with the Java compiler and virtual machine Every character string is an object in Java "Hello", "world",... The behavior of character string objects is defined by the String class Every String literal, delimited by double quotation marks ("), is represented by a String object COMP-202 - Basics of Using Objects 82

Strings in Java (1) 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 However, there are important differences between primitive data types and String objects 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 COMP-202 - Basics of Using Objects 83

Strings in Java (2) 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 COMP-202 - Basics of Using Objects 84

String Concatenation The string concatenation operator (+) is used to append one String to the end of another "hello " + "world" results in a new String This new String will be "hello world" It can also be used to append the String representation of a number to any regular String: int count = 3; String title = "The " + count + " Little" + " Pigs"; System.out.println(title); // Displays "The 3 Little Pigs" COMP-202 - Basics of Using Objects 85

String Caveat A String literal cannot be broken across two lines of source code by inserting and end-of-line sequence in it If you really need to split a String literal across two lines in your program, break the original literal into two smaller String literals and combine them with the concatenation operator The following code fragment causes an error: "This is a very long literal that spans two lines" // Incorrect! However, the following code fragment is legal: "These are two shorter literals " + "that are on separate lines" // OK COMP-202 - Basics of Using Objects 86

Facts.java public class Facts { public static void main(string[] args) { String firstname = "Cuthbert"; String lastname = "Calculus"; String fullname; } } fullname = firstname + " " + lastname; System.out.println("His name is: " + fullname); System.out.println("Phone number: (" + 888 + ") " + 555 + "-" + 1234); What is the output? COMP-202 - Basics of Using Objects 87

Concatenation and Mixing Types The plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the type of the information on which it operates Strings are considered to have higher precision than numeric types If both operands are of type String, or if one is of type String and the other is numeric, the + operator performs string concatenation (after "promoting" the numeric operand, if any, to type String) If both operands are numeric, it adds them The + operator is evaluated left to right Parentheses can be used to force the operation order COMP-202 - Basics of Using Objects 88

Addition.java public class Addition { public static void main(string[] args) { int x = 5; int y = 2; int sum = 0; String message = "The sum is "; } } sum = x + y; message = message + sum; System.out.println(message); What is the output? COMP-202 - Basics of Using Objects 89

Trick Question (1) What will be the output of the following code fragment? System.out.println("The sum of 5 and 3 is " + 5 + 3); The answer is: The sum of 5 and 3 is 53 (?!?) Explanation: The + operator is evaluated from left to right Thus, it is first applied to "The sum of 5 and 3 is " and the int literal 5 to form the String "The sum of 5 and 3 is 5" Then, we apply the + operator to the result from the previous concatenation operation and the int literal 3 to get "The sum of 5 and 3 is 53" COMP-202 - Basics of Using Objects 90

Trick Question (2) What will be the output of the following code fragment? System.out.println(5 + 3 + " is the sum of " + "5 and 3"); The answer is: 8 is the sum of 5 and 3 (?!?) Explanation: Again, the + operator is evaluated from left to right Thus, it is first applied to the int literals 5 and 3; both of these have numeric type, so addition is performed and the sum is 8 Then, the + operator is applied to the result of the addition and the String literal " is the sum of "; the sum is converted from int to String and concatenated with the String literal COMP-202 - Basics of Using Objects 91

Trick Question (3) Finally, the String literal "5 and 3" is concatenated to the String "8 is the sum of " to form the String "8 is the sum of 5 and 3" Lesson: When in doubt, use parentheses COMP-202 - Basics of Using Objects 92

Escape Sequences What if we wanted to print a double quotation mark? The following line would confuse the compiler because it would interpret the second double quotation mark as the end of the String literal: System.out.println("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character that follows should be treated in a special way: System.out.println("I said \"Hello\" to " + "you."); COMP-202 - Basics of Using Objects 93

Java Escape Sequences Some escape sequences in Java: Escape sequence Meaning \b \t \n \r \" \' \\ Backspace Tab New line (line feed) Carriage return Double quotation mark (String) Single quotation mark (char) Backslash COMP-202 - Basics of Using Objects 94

Poem.java public class Poem { public static void main(string[] args) { System.out.println("Roses are red,"); System.out.println("\t Violets are blue"); System.out.println("\t This poem " + "sucks\n\t I wish it were a haiku"); } } What does this display? COMP-202 - Basics of Using Objects 95

Haiku.java public class Haiku { public static void main(string[] args) { System.out.print("\t Windows Vista crashed."); System.out.print("\n\t I am the Blue Screen " + "of Death.\n"); System.out.println("\t No one hears your screams."); } } What does this display? COMP-202 - Basics of Using Objects 96

Creating String Objects Because String objects are so common, we do not have to use the new operator to create one; 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 COMP-202 - Basics of Using Objects 97

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. COMP-202 - Basics of Using Objects 98

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. COMP-202 - Basics of Using Objects 99

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 COMP-202 - Basics of Using Objects 100

String Indexing (1) 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' COMP-202 - Basics of Using Objects 101

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 COMP-202 - Basics of Using Objects 102

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

Reading Exception Output (2) 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:9) More details on the problem Index we tried to access and caused the crash COMP-202 - Basics of Using Objects 104

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? COMP-202 - Basics of Using Objects 105

Part 4: The Java Standard Library

Class Libraries A class library is a collection of classes that we can use when developing programs There is a Java standard class library that is part of any Java development environment 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 Other class libraries can be obtained through third party vendors, or you can create them yourself COMP-202 - Basics of Using Objects 107

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 COMP-202 - Basics of Using Objects 108

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 COMP-202 - Basics of Using Objects 109