Lecture Notes for CS 150 Fall 2009; Version 0.5

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

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

STUDENT LESSON A10 The String Class

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

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

Full file at

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

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

First Java Program - Output to the Screen

Use of objects and variables

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

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

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

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

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

1007 Imperative Programming Part II

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

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

Intro. Scheme Basics. scm> 5 5. scm>

Week 2: Data and Output

Notes from the Boards Set BN19 Page

Using Java Classes Fall 2018 Margaret Reid-Miller

Chapter. Let's explore some other fundamental programming concepts

CS112 Lecture: Working with Numbers

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

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

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

2.8. Decision Making: Equality and Relational Operators

Appendix: Common Errors

CS 231 Data Structures and Algorithms, Fall 2016

STRINGS AND STRINGBUILDERS. Spring 2019

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

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

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

What did we talk about last time? Examples switch statements

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

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

Chapter 29B: More about Strings Bradley Kjell (Revised 06/12/2008)

CPS122 Lecture: From Python to Java

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Midterms Save the Dates!

CMPT 125: Lecture 3 Data and Expressions

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

download instant at

Program Elements -- Introduction

Chapter 2: Using Data

Basics of Java Programming

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

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Object Oriented Methods : Deeper Look Lecture Three

CS11 Java. Fall Lecture 1

double float char In a method: final typename variablename = expression ;

SDKs - Eclipse. SENG 403, Tutorial 2

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

Lecture 7: Classes and Objects CS2301

Getting started with Java

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

2: Basics of Java Programming

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Basic Computation. Chapter 2

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

Program Fundamentals

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

Computational Expression

BM214E Object Oriented Programming Lecture 8

COMP-202 Unit 5: Basics of Using Objects

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

String. Other languages that implement strings as character arrays

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

Java Bytecode (binary file)

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Mobile App:IT. Methods & Classes

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

The compiler is spewing error messages.

Using System.out.println()

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

Chapter 2: Data and Expressions

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.

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Strings, Strings and characters, String class methods. JAVA Standard Edition

Topics. Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Section 2: Introduction to Java. Historical note

Introduction to Java Applications

Chapter 8: Strings and Things

CS 106 Introduction to Computer Science I

CS 101 Fall 2006 Midterm 1 Name: ID:

Transcription:

for CS 150 Fall 2009; Version 0.5 Draft! Do not distribute without prior permission. Copyright 2001-2009 by Mark Holliday Comments, corrections, and other feedback appreciated holliday@email.wcu.edu Chapter 2: Using the Class Section 1: Method Signatures and Overloading Section 2: Literals and Return Values Section 3: Losing Return Values Section 4: Variable Declaration Statements Section 5: Assignment Statements Section 6: Implications of Reference Variables Section 7: Methods Section 8: Method Cascading and Composition There are two predefined objects that we will use significantly in the course. One is the PrintStream object referenced by the variable System.out and the other is the InputStream object referenced by the variable System.in. The PrintStream class has only two methods that we will use: println which we have already used and print. The difference is that print does not insert a newline character into the output. In other words, on the screen, a print method call does not move the cursor down to the next line. In contrast, the println method does. In fact, println is pronounced "print line". We will never use the InputStream class directly since it does not have the method we want to use for reading input. The method we want to use is called nextline and is a method of the Scanner class. In chapter 3 we learn how to create a Scanner object from an InputStream object. What this chapter is about is the class. The class is important in Java programs and since we are not going to discuss primitive types (such as the int type that represents integers) until chapter 5, the class is one of the main examples with which we will work. In using the class we will not be using predefined 1

objects; we will creating new objects. However, the way that we will be creating objects is a special way that just works with the class. The more general way to create objects will be discussed in the next chapter. In this chapter we will use the class to create objects and to practice using many of the methods that come with the class. We also discuss further the important idea of variables. Section 1: Method Signatures and Overloading Above we said that PrintStream has a method named println and a method named print. Actually, that is not quite true; PrintStream has two methods that are both named println as well as a method named print. To explain how this is possible we have to be more precise about how methods are characterized. As described in Chapter 1, a method is called by the general format reference. methodname ( argumentlist) where there is a reference to the object that has the method, followed by a dot, followed by the name of the method, followed by a left parenthesis, followed by list of arguments, followed by a right parenthesis. The reference makes clear which object is being used and each object is an instance of some class. Thus, we know we are using one of the methods associated with a particular class. Of the methods for that class if two have the same name, then the argument list must be used to distinguish between them. Such a situation is called an example of method overloading. The exact rule is that two methods of the same class must 1) have different names or 2) have the same name and a different number of arguments or 3) have the same name and the same number of arguments but at least one pair of corresponding arguments have different types. For example, if one method has a reference to a as its first argument and the other method has a reference to a PrintStream as its first argument, then the methods are distinct. In short the requirement is that the methods must have different signatures where a method's signature is its name and argument list. Here is an example using the three methods of the PrintStream class for printing. class PrintExample { public static void main([] args) { System.out.println("A string, then next line,"); System.out.println("and then a blank line."); 2

} } System.out.println(); // causes move to next line System.out.print("Just a string,"); System.out.print(" all on the same line."); System.out.println(); System.out.println("Hi"); The output is A string, then next line, and then a blank line. Just a string, all on the same line. Hi. Section 2: Literals and Return Values A literal is a sequence (or ) of characters between double quotes. We have used them as the argument to the println method of the PrintStream class. literals can be used in other situations and even as an argument there is more going on behind the scenes then we have discussed. The class is special in that it is the only class that has literal values. When a literal is used what really is happening is that 1. an instance of the class (that is, a object) is created, 2. that object is given the value of the literal, and 3. a reference to that object is also created with the literal representing the reference For example, the literal "wcu" creates the diagram shown in Figure 2.1. The new object has the value "wcu" inside it and "wcu" is also thought of as representing the reference to that object. 3

"wcu" "wcu" Figure 2.1. The object and reference created by the literal "wcu". Once we have a reference to an object we can use that reference to call a method of that object. That is what we did with System.out.println("Hi"); since System.out is a variable holding a reference to a PrintStream object and println is a method that PrintStream objects have. The only difference is that in the case of "wcu" the reference is not being held by a variable. Instances of the class are immutable. The value within a object can not be changed after the object is created. To simulate changing a object, it is necessary to create a new object that has a value which is a modification of the value of the original object. A object can have a value which is an empty sequence of characters. The literal for this object is ""; that is, the double quote for the start of the immediately followed by the double quote which is the end of the. A variable that is not holding a reference to a object is different from a variable that is holding a reference to a object that is the empty. Figure 2.2a illustrates a variable that is not holding a reference to an object and Figure 2.2b illustrates a variable that reference a object that is the empty. 4

foo foo (a) (b) "" Figure 2.2. Memory diagram for a) an empty variable, and b) a variable holding a reference to a object that is an empty. One method of the class is called touppercase. We can call that method by "wcu".touppercase() Figure 2.3 shows this method call as the wavy arrow going from the reference "ibm" to the method touppercase. The wavy arrow has empty parentheses next to it, to indicate that there are no arguments. The "ibm" that is the reference is not inside a rectangle since it is not in a variable. 5

"wcu".touppercase() arguments reference method name "wcu" () "wcu" touppercase "WCU" Figure 2.3. The diagram for the method call "wcu".touppercase(). So "wcu".touppercase() is a new example since it illustrates a method from the class while before we have just talked about methods of the PrintStream class. It is also new in that the reference is created from a literal instead of being held within a predefined variable. It is also new in that it illustrates how literals automatically create objects. It also is new in that it is our first method that has a return value. All of the println and print methods just perform their action and then execution returns to the calling code. The touppercase method adds a new feature called a return value. A return value means that when execution returns to the calling code, a value is returned also. The value that the touppercase method of the class returns is a reference to a object. With respect to method overloading all that matters is the method name and the argument list. However, whether a method returns a value and if it returns a value, what type of value it returns, is an important aspect of the description of a method. Here is a table [page 29 of AW] describing the methods we have so far introduced. 6

Class Method Return value Argument List PrintStream println None None PrintStream println None One argument which is a reference to a object PrintStream print None One argument which is a reference to a object touppercase Reference to a object none Section 3: Losing Return Values When a method call returns a value something has to be done with that value or will it be lost. In particular, the following code fragment is a very common bug for beginning Java programmers. System.out.println( "The following method call returns a value."); "cs150 is wonderful".touppercase(); System.out.print( "However, nothing is done with the return value "); System.out.println("so it is lost."); The whole point of the touppercase method is to create an object which is an all uppercase version of the that it is a method of. However, if the returned reference to that object is not used, then there is no way of accessing the new object. So how can the returned value be used? It can be used immediately or it can be saved for later use. One way to use it immediately is to make that reference be an argument to another method call. Here is such an example System.out.println("cs150 is wonderful".touppercase()); This example will display on the screen CS150 IS WONDERFUL In this example, the return value from the touppercase method call is being used as 7

the argument to the println method call. This works since the type of the return value is reference to and that is the type that is required for the argument to the println method. In understanding the above example, or any example using a return value, the key is to think of the return value as replacing the method call that generates the return value. So think of the above example as having the effect of System.out.println( reference to a object ); where reference to a object is not Java code but just stands for the reference that is returned from the method call. This way of using a reference immediately is called method composition. A second way of using a return value which is a reference immediately is to use it to call a method of the new object. This is called method concatenation and we will see some examples of this later in this chapter. There are other ways of using a return value immediately which are especially useful when we look at return values which are of primitive types. Primitive types are discussed in Part B of these notes. Section 4: Variable Declaration Statements Instead of using a return value immediately, many times it is smart to save it and then later use it. Once it is saved it can be used over and over again. The way to store a return value is to store it in a variable. A variable has a name (its identifier) and can hold a value. One kind of a value is a reference to an object. So far the only variable that we have seen is the predefined variable System.out. We can create our own variables using a variable declaration statement. Such a statement has the form of the type of the variable followed by the name of the variable. An example of the simplest version is stringvalue; // declares one variable named stringvalue //that can hold a reference to a object // but is not currently holding a reference Several variables can be declared in a single declaration statement as long as they are all 8

of the same type. For example, first, second, third; // declares three variables named first, second, // and third all of these variables can hold a // reference to a object but // currently none of them is holding a reference This second form of variable declarations has some limitations. As discussed later there are actually three kinds of variables: fields, parameters, and local variables. The examples we are currently considered are all local variables. This second form of variable declarations where the type is listed once for several variables is not legal Java syntax when declaring a variable that is a parameter. Trying to use this form when declaring several parameters (that is, in a parameter list) is a common bug for beginning students. For fields and local variables this second form of variable declarations is legal Java. However, programming style guidelines restrict its use. In particular, our departmental guidelines prohibit its use for fields. The reason is that each field is important enough to warrant a separate declaration statement. Our guidelines allow this form for local variables, but only three variables can be declared in a single such statement. The reason is that declaring many variables in a single statement makes the code more difficult to read. There is a third form for variable declaration statements that we will see after introducing assignment statements. This third form includes an initialization as part of the declaration. Section 5: Assignment Statements The most common way to cause a variable to hold a value is by using an assignment statement. In particular an assignment statement can be used to save the return value from a method call into a variable. Assignment statements are important and also, unfortunately, students sometimes have trouble reading them correctly at first. An assignment statement has four parts which are in order from left to right: a left-hand side (LHS), an equal sign, a right-hand side (RHS), and a semi-colon. The key point is that you need to read an assignment statement from right-to-left, not leftto-right. This is what often confuses beginning students since we are all used to reading left-to-right. You read the RHS first. The RHS is an expression. The concept of an 9

expression is very important and the details will be discussed later. For now all we need to know is that an expression is something that evaluates to a value. The one expression that we have been using is a method call. The value that a method call expression evaluates to is the return value of that method call. The LHS side must be a variable since the point of an assignment statement is to cause the value which is the RHS to become the new value held by the variable which is the LHS. The equal sign in the middle is called the assignment operator since it is thought of as doing the actual assigning; that is, the actual placing of the RHS value into the LHS variable. To help the student remember that the equal sign means assignment and not equality, I read the equal sign as the word gets. Thus, in the example. stringvalue; stringvalue = "how are you?"; The second statement is read as The variable stringvalue gets the "how are you?" In this example, recall that the "how are you?" literal causes a object to be created that holds the value "how are you?" and the literal also represents a reference to that object. Thus the right-hand side is a reference to a object. The assignment causes the variable stringvalue to be assigned, or get, a copy of that reference. Part a) of Figure 2.4 shows the memory diagram for this example after just the right-hand side has executed. Part b) of Figure 2.4 shows the memory diagram after the entire statement has executed. "How are you?" stringvalue "How are you?" (a) "How are you?" (b) "How are you?" 10

Figure 2.4. a) The memory diagram after the right-hand side of the statement has executed. b) The memory diagram after the assignment statement stringvalue = "how are you?"; has completed execution. Another example assignment statement has a method call as the RHS. In this case, the RHS evaluates to the return value of that method call. Here is an example, stringvalue = "hello".touppercase(); Figure 2.5 is the memory diagram showing the result of the execution of this statement. This example illustrates how the return value from a method call can be saved in a variable. "hello" "hello" "hello" "hello" "hello" "hello" touppercase "HELLO" : stringvalue "HELLO" (a) (b) (c) Figure 2.5. The object diagram for the assignment statement stringvalue = "hello".touppercase();. a) shows the calling of the method, b) shows the situation after the return from the method call, and c) shows the situation after the assignment of the return value to the variable stringvalue. The RHS must evaluate to a value so having a method call being the RHS only makes sense if the method returns a value. For example, have a println method call as a RHS does not make sense since there is no return value to then assign to the LHS. stringvalue = System.out.println(); 11

// WRONG! Not legal Java since the RHS does not // evaluate to a value We have now seen three kinds of Java statements: method call statements, variable declaration statements, and assignment statements. There is a third form of variable declaration statements that is a combination of a variable declaration and an assignment statement. Here is an example name = "John Smith"; This is called a declaration with an initialization. The value on the right-hand side is assigned to the variable that is declared on the left-hand side. As mentioned earlier, variables are useful since they can be used to store a value and reuse that value later. The only kind of value we have seen so far is a reference. Thus, for example [page 30 of AW] instead of System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); we can do line = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); System.out.println(line); System.out.println(line); System.out.println(line); which is quite a bit shorter. In this example the variable line is holding a reference to a object. That reference can be used to call a method on that object. For example, greeting = "Hello"; biggreeting; // Figure 2.6a shows after this statement biggreeting = greeting.touppercase(); // Figure 2.6b shows after this statement System.out.println(bigGreeting); Figure 2.6 shows the memory diagrams for this code fragment after the declaration of the variable biggreeting and the assignment to variable biggreeting. 12

greeting biggreeting greeting biggreeting () "hello" "hello" touppercase "HELLO" "hello" (a) "hello" (b) Figure 2.6. a) Memory diagram after declaration of variable biggreeting, and b) memory diagram after assignment to variable biggreeting. All the variables should have the word before the variable name, but it is not shown due to limited space. Section 6: Implications of Reference Variables When a variable is declared, it is declared to be of a particular type (such as or PrintStream). For all the variables that we are currently considering, that type is a class. When the type of a variable is a class, then the value held by the variable is a reference to an instance of that class or is the special value called null. The null value will be discussed later. Variables that can hold references (that is, have a class as their type) are called reference variables. In this section we discuss some implications of the fact that reference variables can hold references. The first point is that a variable can only hold a reference for an object of the variable's type. It is illegal to try to assign to the variable a reference to another kind of object. s; PrintStream p; s = System.out; // WRONG! since s can only hold a reference to a // object and PrintStream holds a // reference to a PrintStream object 13

p = "Hello"; // WRONG! Since p can only hold a reference // to a PrintStream // object and "Hello" is a reference to a // object s = "Hello"; // fine p = System.out; // fine The second point is that the reference that a variable is holding can change and that a variable can only hold one reference at a time. t; t = "Springtime"; t = "Wintertime"; Figure 2.7 shows the memory diagram after the last of these statements. Notice that the object "Springtime" has no reference pointing to it. If an object has no reference pointing to it, then there is no way for the program to access that object. The Java virtual machine will eventually detect such objects and delete them. That process is called automatic garbage collection. Automatic garbage collection is an important difference from C++. In C++ garbage collection has to be done explicitly by the programmer. "SpringTime" "WinterTime" : t Figure 2.7. The memory diagram after the statements where variable t has its value changed. The third point is that even though a variable can only reference one object at a time, one object may have several references to it simultaneously. Consider this fragment s, t; s = "Springtime"; t = s; 14

Figure 2.8 shows the memory diagram after the execution of these statements. "SpringTime" : s : t Figure 2.8. The memory diagram for the code fragment where s and t both hold references to the same object. A fourth point is that variables are independent so that two variables both hold references to the same object, does not mean that changes to one of those variables will change the other variable. For example, consider the following code fragment. Figure 2.9 shows the memory diagram after the execution of this fragment. s, t; s = "Inventory"; t = s; s = "Payroll"; : t : s "Inventory" "Payroll" Figure 2.9. The memory diagram for the code fragment where two variables are referencing the same object and then one of the variables has its reference changed. The last point is that when a variable is used in an assignment statement, how the variable is used depends on whether the variable is on the left hand side or the right hand side. If it is on the right hand side, then when the statement is executed the content of the variable (which is a reference) is retrieved. If the variable is on the left hand side, then when the 15

statement is executed, the variable is used as the storage place to hold the result of evaluating the right hand side of the statement. Section 7: Methods So far we have only used one method, touppercase, of the class. We now introduce several other methods. The table [page 38 of AW] below lists these methods. touppercase tolowercase Method Returns Arguments Reference to a object Reference to a object None None length A number None trim concat substring substring Reference to a object Reference to a object Reference to a object Reference to a object None Reference to a object A number Two numbers The length method returns how many characters are in the. The trim method removes space characters and tab characters from the beginning and end of the. The concat method creates a new that is the concatenation of the current and the that is the argument. Here is a fragment illustrating these three methods. s = " blue "; // there are two spaces before the "b" and // after the "e" System.out.println(s.length()); s = s.trim(); System.out.println(s); System.out.println(s.length()); s = s.concat(s); 16

System.out.println(s); // Figure 2.10 shows the result of the last // two statements The output of this fragment is 8 blue 4 blueblue Of these three methods perhaps the most interesting is concat since it takes a reference to a as an argument and creates a new. Figure 2.10 is the memory diagram for the second to last statement in the above fragments. That statement illustrates concatenation. : s : s ( ) "blue" "blue" "blueblue" concat Figure 2.10. The memory diagram for the statements illustrating concatenation. The characters that form a can be specified by position. The first character in the s is at position 0, the second character is at position 1, and the last character is a position s.length() - 1. The position number is called the index of that character. The two substring methods use these position numbers in creating a new. The substring method with one argument creates a new that is the substring of the current that starts at the position specified by the integer argument and goes to the end of the current. The substring method with two arguments creates a new that is the substring of the current that starts at the position specified by the first argument and goes to, but does not include, the position specified by the second 17

argument. Here is a code fragment and figure, Figure 2.11, illustrating the one argument substring method. s, t; s = "hamburger"; t = s.substring(3); : s (3) : t "hamburger" substring "burger" Figure 2.11. Memory diagram for the fragment illustrating the one argument substring method. Here is a code fragment and figure, Figure 2.12, illustrating the two argument substring method. s, t; s = "hamburger"; t = s.substring(3, 7); 18

: s "hamburger" (3, 7) substring : t "burg" Figure 2.12. Memory diagram illustrating the two argument substring method. Section 8: Method Cascading and Composition We have considered three kinds of statements: method call statements, variable declaration statements, and assignment statements. It is possible to construct method call statements that involve more than one method call. There are two ways to do this: method cascading and method composition. This section describes these two ways. Sometimes invoking more than one method in a single statement is a good idea and sometimes it is not The advantage is that the code is shorter which means that the programmer does not have to write as much and does not have to create some extraneous variables. The disadvantage is that the code is shorter which means that the code can sometimes be less readable. When shorter code is an improvement is subjective. In any case, it is useful to know how to use method cascading and composition to shorten a code fragment. Of the two approaches method composition is more widely used and usually more readable. Method cascading is only possible when the first method called returns a reference. In this case, the returned reference can be immediately used to call a method of that object referenced. Here is an example code fragment and corresponding figure, Figure 2.13, not using method cascading. first = "Blue"; second = "Green"; third = "Red"; temp, last; // use the name last instead of final since // final is a reserved word 19

// not using method cascading temp = first.concat(second); last = temp.concat(third); // last is "BlueGreenRed" first second (second) concat "Blue" "Green" temp (third) "BlueGreen" concat third "Red" "BlueGreenRed" last Figure 2.13. Memory diagram for fragment without method cascading. All the variables should have the word before the variable name, but it is not shown due to limited space. Here is the same code fragment and corresponding figure, Figure 2.14, but with method cascading. The use of the variable temp is avoided. The reference returning from first.concat(second) is immediately used to call the concat method of the new object. first = "Blue"; second = "Green"; third = "Red"; last; // using method cascading last = first.concat(second).concat(third); // last is "BlueGreenRed" 20

first second (second) concat "Blue" "Green" (third) "BlueGreen" concat third "Red" "BlueGreenRed" last Figure 2.14. Memory diagram for fragment with method cascading. Notice that the only difference in the figure is that the variable named temp does not exist. Instead the reference to the object holding the value "BlueGreen" is not inside a variable. All the variables should have the word before the variable name, but it is not shown due to limited space. Method composition also involves multiple method calls and also, like method cascading, requires the first method call to have a return value. Method composition is actually more widely applicable since the return value from the first method call does not have to be a reference. It can be another type of value (a primitive type value), but we will not discuss primitive types until later. Here are two code fragments and corresponding figures. The first fragment and figure, Figure 2.15, show the use of a temporary variable instead of method composition. The second fragment and figure, Figure 2.16, use method composition and avoid a temporary variable. first = "Blue"; second = "Green"; third = "Red"; temp, last; 21

// not using method composition temp = first.concat(second); last = third.concat(temp); // last is "RedBlueGreen" first second (second) concat "Blue" "Green" temp third (temp) concat "BlueGreen" "Red" "RedBlueGreen" last Figure 2.15. Memory diagram for fragment without method composition. All the variables should have the word before the variable name, but it is not shown due to limited space. first = "Blue"; second = "Green"; third = "Red"; last; // using method composition last = third.concat(first.concat(second)); // last is "RedBlueGreen" 22

first second (second) concat "Blue" "Green" third ( ) concat "BlueGreen" "Red" "RedBlueGreen" last Figure 2.16. Memory diagram for fragment with method composition. All the variables should have the word before the variable name, but it is not shown due to limited space. To get the final string to be BlueGreenRed using method composition replace the above last statement by last = first.concat(second.concat(third)); // last is "BlueGreenRed" 23