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

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

Lecture Notes for CS 150 Fall 2009; Version 0.5

STUDENT LESSON A10 The String Class

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

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

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

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

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

More non-primitive types Lesson 06

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

CMPT 125: Lecture 3 Data and Expressions

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

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Full file at

Lab 14 & 15: String Handling

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

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

BM214E Object Oriented Programming Lecture 8

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

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

Getting started with Java

Programming with Java

Chapter 8: Strings and Things

STRINGS AND STRINGBUILDERS. Spring 2019

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

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

COE318 Lecture Notes Week 4 (Sept 26, 2011)

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

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

More on variables and methods

appreciate the difference between a char and a string understand and use the String class methods

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Using System.out.println()

5. Control Statements

CS112 Lecture: Characters and Strings

6.001 Notes: Section 8.1

Java Foundations: Unit 3. Parts of a Java Program

Fall 2017 CISC124 10/1/2017

CS 116x Winter 2015 Craig S. Kaplan. Module 09 Text Processing. Topics

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

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Student Performance Q&A:

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

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Class. Chapter 6: Data Abstraction. Example. Class

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Lecture Topics. Administrivia

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

CHAPTER 7 OBJECTS AND CLASSES

String. Other languages that implement strings as character arrays

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

COMP-202 Unit 5: Basics of Using Objects

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Activity 9: Object-Oriented

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

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

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

Java Bytecode (binary file)

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

Output with printf Input. from a file from a command arguments from the command read

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

Bits, Words, and Integers

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

Account joeacct = new Account (100, new Account (500)); Account joeacct = new Account (100, new Account (500, null));

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

CHAPTER 7 OBJECTS AND CLASSES

First Java Program - Output to the Screen

A couple of decent C++ web resources you might want to bookmark:

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

Variables and Data Representation

do fifty two: Language Reference Manual

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

String Theory. Chapter Cut and Paste

CS 1301 Ch 8, Part A

QUIZ. What is wrong with this code that uses default arguments?

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

Chapter 3: Operators, Expressions and Type Conversion

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

COMP 105 Homework: Type Systems

CE221 Programming in C++ Part 1 Introduction

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CS 106 Introduction to Computer Science I

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CS260 Intro to Java & Android 03.Java Language Basics

Section 2: Introduction to Java. Historical note

Types and Expressions. Chapter 3

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

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

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

Transcription:

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008) In previous chapters, methods were called with parameters that were primitive data types. This chapter discusses how to use object references as parameters. The class String is used in many examples. Chapter Topics: String literals The null value More about garbage The String class String concatenation Strings are immutable Some String methods o concat() o length() o trim() o substring() o tolowercase() o startswith() o charat() Cascading methods Students taking the computer science Advanced Placement examination are expected to be familiar with the String class. QUESTION 1: (Review:) What TWO things does the following statement do? String zeta = new String( "The last rose of summer." ); Used by permission. Page 1 of 38

A new String object is created, containing the characters between quote marks. A reference to the object is saved in the variable zeta. Easy way to Construct Strings String objects are very useful and are frequently used. To make life easier for programmers, Java has a short-cut way of creating a String object: String zeta = "The last rose of summer." ; This creates a String object containing the characters between quote marks. A String created in this short-cut way is called a String literal. Remember that if several statements in a program ask for literals containing the same characters, only one object will actually be constructed (see chapter 26). Other classes do not have short-cuts like this. Objects of most classes are constructed by using the new operator. QUESTION 2: Can a String reference be a parameter for a method? Used by permission. Page 2 of 38

Yes, a String reference is often a parameter. String References as Parameters Some methods require a parameter that is a reference to a String object. For example, The picture that shows how the method call works. (Both objects have many methods, but only the equals() method of one object is pictured.) The String object referred to by stringa has an equals() method. That method is called with a parameter, a reference to another String object, stringb. The method checks if both String objects contain identical sequences of characters, and if so, evaluates to true. Careful: The previous paragraph is correctly stated, but awkward. People often say "String" when they really mean "reference to a String". This is fine, but remember that a reference variable like stringa does not contain an object, but only a reference to an object. This may seem picky, but there is nothing quite as picky as a computer. Students who are not careful about this often run into problems. Used by permission. Page 3 of 38

QUESTION 3: (Review:) Examine the following snippet of code. Answer the questions using careful words (like the above on the right). String a; Point b; What is the data type of the variable a? What is the data type of the variable b? How many objects are there (so far)? Used by permission. Page 4 of 38

What is the data type of the variable a? o a is a reference to a String object. What is the data type of the variable b? o b is a reference to a Point object. How many objects are there (so far)? o So far, there are no objects, just variables that can reference objects, once there are some. The null Value A reference variable holds information about the location of an object. It does not hold the object itself. This code String a; Point b; declares two reference variables but does not construct any objects. The following constructs objects and puts references in the variables: a = "Elaine the fair" ; b = new Point( 23, 491 ); null is a special value that means "no object." Your program should set a reference variable to null when it is not referring to any object. Programs often set variables to null when they are declared: String a = null; Point b = null; QUESTION 4: (Thought Question:) Do you think that null can be assigned to reference variables of any type? Hint: How many types of nothing are there? Used by permission. Page 5 of 38

Yes. Null Assigned to any Reference Variable It would be awful if each class had its own special value to show that no object of that class was present. We need a universal value that means "nothing here". The value null works for this and can be assigned to any reference variable. In most programs, objects come and objects go, depending on the data and on what is being computed. (Think of a computer game, where monsters show up, and monsters get killed). A reference variable sometimes does and sometimes does not refer to an object, and can refer to different objects at different times. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable. Inspect the code below. Variables a and c are initialized to object references. Variable b is initialized to null. QUESTION 5: What exactly is variable c initialized to? Consider: the absence of paper and a blank sheet of paper. Used by permission. Page 6 of 38

The code "" calls for a literal, which is a String object. Although the object exists, it contains no characters (since there are no characters inside ""). The reference variable c is initialized to a reference to this String object. This is most certainly a different value than null. The Empty String A String object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper, versus having no paper at all. Overlooking this distinction is one of the classic confusions of computer programming. It will happen to you. It still happens to me. To prepare for future confusion, study this program, step-by-step: Used by permission. Page 7 of 38

The System.out.println() method expects a reference to a String object as a parameter. The example program tests that each variable contains a String reference before calling println() with it. (If println() gets a null parameter, it prints out "null" which would be OK. But some methods crash if they get a null parameter. Usually you should ensure that methods get the data they expect.) QUESTION 6: Examine the following code snippet: String alpha = new String("Red Rose") ; alpha = null;... Where is an object constructed? What becomes of that object? Used by permission. Page 8 of 38

String alpha = new String("Red Rose") ; alpha = null;... Where is an object constructed? In the first statement. What becomes of that object? It became garbage in the second statement. Garbage The first statement does two things: (1) a String object is created, containing the characters "Red Rose". Then, (2) a reference to that object is saved in the reference variable alpha. The second statement assigns the value null to alpha. When this happens, the reference to the object is lost. Since there is no reference to the object elsewhere, it is now garbage. The line through the box in the second statement symbolizes the null value. The object still exists in memory. The memory it consists of will eventually be recycled by the garbage collector and will be made available for new objects. Used by permission. Page 9 of 38

QUESTION 7: Examine this (slightly altered) snippet of code: String alpha = new String("Red Rose"); String beta = alpha; alpha = null;... 1. Where is an object created? 2. What happens in the second statement? 3. What becomes of that object? Used by permission. Page 10 of 38

String alpha = new String("Red Rose"); String beta = alpha; alpha = null; When was an object instantiated? In the first statement. What happenes in the second statement? The reference to the object is copied to beta. What becomes of that object? It remains "alive," because there is still a reference to it. Not Garbage Used by permission. Page 11 of 38

This time, the object does not become garbage. This is because in the second statement a reference to the object is saved in a second variable, beta. Now when, in the third statement, alpha is set to null, there is still a reference to the object. There can be many copies of the reference to an object. Only when there is no reference to an object anywhere does the object become garbage. QUESTION 8: (Review:) How can you determine what an object of a particular class can do? Used by permission. Page 12 of 38

The variables and methods of a class will be documented somewhere. Class String With a Java development environment such as such as Borland JBuilder or Symantec Café the documentation is in the environment (in the editor, put the cursor over a class name and push F1). If you downloaded Java from Sun Microsystems, you might have downloaded the documentation for it, also. Otherwise, use Google or other search engine. To find documentation for class String search for Java String. Here is a short version of the documentation for String. Used by permission. Page 13 of 38

The documentation first lists constructors. Then it describes the methods. For example, public String concat(string str); --+--- --+--- --+-- ----+---- +---- says that the method requires a String reference parameter +----- the name of the method +----- the method returns a reference to a new String object +----- anywhere you have a String object, you can use this method public will be explained in greater detail in another chapter. QUESTION 9: Is the following code correct? String first = "Red " ; String last = "Rose" ; String name = first.concat( last ); You don't have to know what concat() does (yet); look at the documentation and see if all the types are correct. Used by permission. Page 14 of 38

Yes. The concat() Method The parts of the statement match the documentation correctly: String name = first.concat( last ); ----+---- --+-- --+-- --+-- +---- a String reference parameter +----- the name of the method +----- dot notation used to call an object's method. +----- the method returns a reference to a new String object The concat method performs String concatenation. A new String is constructed using the data from two other Strings. In the example, the first two Strings (referenced by first and last) supply the data that concat() uses to construct a third String (referenced by name.) String first = "Red " ; String last = "Rose" ; String name = first.concat( last ); The first two Strings are NOT changed by the action of concat(). A new String is constructed that contains the characters "Red Rose". Used by permission. Page 15 of 38

The picture shows the operation of the concat() method before the reference to the new object has been assigned to name. QUESTION 10: (Review:) Have you seen String concatenation before? Used by permission. Page 16 of 38

Yes: in output statements like this: System.out.println( "Result is:" + result ); The + operator is a short way of asking for concatenation. (If result is a number, it is first converted into characters before the concatenation is done.) Used by permission. Page 17 of 38

+ Operat Here the + operator is used instead of using the concat() method: String first = "Red " ; String last = "Rose" ; String name = first + last ; String concatenation, done by concat() or by +, always constructs a new object based on data in other objects. Those objects are not altered at all. When the operands on either side of + are numbers, then + means "addition". If one or both of the operands is a String reference, then String concatenation is performed. When an operator such as + changes meaning depending on its arguments, it is said to be overloaded. QUESTION 11: Say that the following statement is added after the others: String reversed = last + first; Does it change first, last, or name? Used by permission. Page 18 of 38

No. It uses the data in last and in first to construct a new object. No objects are altered. Strings are Forever Java was designed after programmers had about 15 years of experience with object oriented programming. One of the lessons learned in those years is that it is safer to construct a new object rather than to modify an old one. (This is because many places in the program might refer to the old object, and it is hard to be sure that they will all work correctly when the object is changed.) Objects of some Java classes cannot be altered after construction. The class String is one of these. Sometimes immutable objects are called write-once objects. Once a String object has been constructed, the characters it contains will always be the same. None of its methods will change those characters, and there is no other way to change them. The characters can be used for various purposes (such as in constructing new String objects), and can be inspected. But never altered. Confusion Alert!! This is a place where it is important to distinguish between reference variables and their objects. A reference variable referring to a String can be altered (it can be made to point to a different String object.) The String object it refers to cannot be altered. QUESTION 12: Inspect the following code: String ring = "One ring to rule them all, " String find = "One ring to find them." ring = ring + find; Does the last statement violate the rule that Strings are immutable? Used by permission. Page 19 of 38

No. The String objects don't change. The reference variable ring is changed in the third statement to refer to a different String than originally. (Its original String becomes garbage, which is collected by the garbage collector.) The Length of a String The length of a string is the number of characters it contains, including space characters and punctuation. For example: An empty string has length zero. The length() method of a String returns its length: public int length(); The method takes no parameters, but the () is needed when it is used. QUESTION 13: Inspect the following code: String stringa = "Alphabet " ; String stringb = "Soup" ; String stringc = stringa + stringb; System.out.println( stringc.length() ) ; What does the code print? Used by permission. Page 20 of 38

13 Don't forget to count the space. The trim() Method Here is a line of the documentation for the String class. public String trim(); The trim() method of a String object creates a new String that is the same as the original except that any leading or trailing space is trimmed off (removed). QUESTION 14: Examine the following code: String userdata = " 745 "; String fixed; fixed = userdata.trim(); Has the trim() method been used correctly? How many objects have been created? Used by permission. Page 21 of 38

Has the trim() method been used correctly? How many objects have been created? 2 Yes trim() with Input data The trim() method creates a new String. The new String contains the same characters as the old one but has whitespace characters (blanks, tabs, and several other non-printing characters) removed from both ends (but not from the middle). So, for example, after the last statement String userdata = " 745 "; String fixed; fixed = userdata.trim(); the new String referenced by fixed will contain the characters "745" without any surrounding spaces. (Usage Note:) This method is often useful. Extraneous spaces on either end of user input is a common problem. QUESTION 15: Inspect the following: String dryden = " None but the brave deserves the fair. " ; System.out.println( " " + dryden.trim() + " " ); What is printed out? Used by permission. Page 22 of 38

None but the brave deserves the fair. charat() The charat(int index) method returns a single character at the specified index. If the index is negative, or greater than length()-1, an IndexOutOfBoundsException is thrown (and for now your program stops running). The return values are primitive char data, hence the values are delimited by single quotes, as in 'S'. String literals would be delimited by double quotes, as in "R". The value returned by charat(int index) is a char, not a String containing a single character. A char is a primitive data type, consisting of two bytes that encode a single character. It has no methods or other data. QUESTION 16: What is the output of the following fragment: String singlea = "A" ; String singleb = new String( "B" ); System.out.println( singlea.length() ); System.out.println( singlea.concat( singleb ) ); What is wrong with the following fragment: char onec = 'C' ; char oned = new char( 'B' ); System.out.println( onec.length() ); System.out.println( oned.concat( onec ) ); Used by permission. Page 23 of 38

String singlea = "A" ; String singleb = new String( "B" ); System.out.println( singlea.length() ); System.out.println( singlea.concat( singleb ) ); outputs: 1 AB The following char onec = 'C' ; char oned = new char( 'B' ); System.out.println( onec.length() ); System.out.println( oned.concat( onec ) ); will not even compile. Line two will not compile because a char is not an object, and so has no constructor. The remaining lines will not compile because a char primitive has no methods. Column Checker Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs. Used by permission. Page 24 of 38

The program is used with redirection (see Chapter 21): C:\>javac ColumnCheck.java C:\>java ColumnCheck < datafile.txt A better program would ask the user for several column numbers to check. QUESTION 17: Will the program crash if a line has fewer than 10 characters? Inspect the statement if ( line.length() > colnum && line.charat( colnum )!= ' ' ) System.out.println( counter + ":\t" + line ); How is the short-circuit nature of && used here? Used by permission. Page 25 of 38

if ( line.length() > colnum && line.charat( colnum )!= ' ' ) System.out.println( counter + ":\t" + line ); The short-circuit operation of && means that line.length() > colnum is tested first. If this result is false, then the next part of the condition is not tested (since the result of AND will be false regardless of its result). So line.charat( colnum ) is only performed when it is certain that the line contains a character at index colnum Substrings A substring of a string is a sequence of characters from the original string. The characters are in the same order as in the original string and no characters are skipped. For example, the following are all substrings of the string "applecart": apple cart pple e lecar You have previously seen (in chapter 9) the substring() method of String objects: public String substring(int beginindex ) This method creates a new substring that consists of the characters from character number beginindex to the end of the string. For example "applecart".substring(5) contains the characters "cart". Remember: character numbering starts with zero. The leftmost character of a string is character zero. The rightmost character is character length-1. QUESTION 18: What is printed by the following code: String source = "applecart"; String sub = source.substring(6); System.out.println( sub ); System.out.println( source ); Used by permission. Page 26 of 38

art applecart Tricky Rules The method public String substring(int beginindex ) creates a new string. The original string is not changed. There are two tricky rules: If beginindex is exactly equal to the length of the original string, a substring is created, but it contains no characters (it is an empty string) If beginindex is greather than the length of the original string, or a negative value, a IndexOutOfBoundsException is thrown (and for now, your program crashes). QUESTION 19: Decide on what string is formed by the following expressions: Used by permission. Page 27 of 38

Another substring() Here is another method of String objects: substring(int beginindex, int endindex) This method creates a new String containing characters from the original string starting at beginindex and ending at endindex-1. Warning: the character at endindex is not included. The length of the resulting substring is endindex-beginindex. QUESTION 20: Examine the following code: String stars = "*****" ; int j = 1; while ( j <= stars.length() ) { System.out.println( stars.substring(0,j) ); j = j+1; } Used by permission. Page 28 of 38

* ** *** **** ***** More Tricky Rules As with the other substring method, this one public String substring(int beginindex, int endindex ) creates a new string. The original string is not changed. There are some tricky rules. Essentially, the rules say that if the indexes make no sense, a IndexOutOfBoundsException is thrown. If beginindex is negative value, an IndexOutOfBoundsException is thrown. If beginindex is larger than endindex, an IndexOutOfBoundsException is thrown. If endindex is larger than the length, an IndexOutOfBoundsException is thrown. If beginindex equals endindex, and both are within range, then an empty string is returned. Usually, when an exception is thrown your program halts. Future chapters discuss how to deal with exceptions QUESTION 21: Decide on what string is formed by the following expressions: Used by permission. Page 29 of 38

Control Characters inside String Objects Recall that control characters are bit patterns that indicate such things as the end of a line or page separations. Other control characters represent the mechanical activities of old communications equipment. The characters that a String object contains can include control characters. For example, examine the following code: The sequence \n represents the control character that ends a line. This control character is embedded in the data of the strings. The object referenced by poem has two of them. The program writes to the monitor: Only to the wanderer comes Ever new this shock of beauty Used by permission. Page 30 of 38

Although you do not see them in the output, the control characters are part of the data in the String. Here is another method from the String class: public String tolowercase(); This method constructs a new String object containing all lower case letters. There is also a method that produces a new String object containing all upper case letters: public String touppercase(); QUESTION 22: Here are some lines of code. Which ones are correct? Used by permission. Page 31 of 38

Temporary Objects The "correct" answer for the last two lines might surprise you, but those lines are correct (although perhaps not very sensible.) Here is why: The temporary object is used to construct a second object. The reference to the second object is assigned to d. Now look at the last statement: System.out.println( "Dark, forlorn...".tolowercase() ); Used by permission. Page 32 of 38

A String is constructed. Then a second String is constructed (by the tolowercase() method). A reference to the second String is used a parameter for println(). Both String objects are temporary. After println() finishes, both Strings are garbage. (There is nothing special about temporary objects. What makes them temporary is how the program uses them. The objects in the above statement are temporary because the program saves no reference to them. The garbage collector will soon recycle them.) QUESTION 23: Tedious review: Can an object reference variable exist without referring to an object? Can an object exist without an object reference variable that refers to it? Used by permission. Page 33 of 38

Can an object reference variable exist that without referring to an object? Yes, a reference variable can be declared without initialization: String mystring; Also, a reference can be set to null. Can an object exist without an object reference variable that refers to it? Yes, as seen in the previous example. Such objects are temporary. The startswith() Method Here is another method of the String class: public boolean startswith(string prefix); The startswith() method tests if one String is the prefix of another. This is frequently needed in programs. (Although this example is too short to show a real-world situation, study it carefully.) Notice how trim() is used in the last if statement. QUESTION 24: What does the program write to the monitor? Used by permission. Page 34 of 38

Prefix 1 matches. Prefix 2 fails. Prefix 3 fails. Prefix 4 matches. More String Operations Here is how the last if of the program worked: The String " My love" starts with two spaces, so it does not match the start of the String referenced by burns. However, its trim() method is called, which creates a new String without those leading spaces: Used by permission. Page 35 of 38

Programmers usually do not think about what happens in such detail. Usually, a programmer thinks: "trim the spaces of one String and see if it is the prefix of another." But sometimes, you need to analyze a statement carefully to be sure it does what you want. Look again at the above statement and practice thinking about it at several levels of detail. QUESTION 25: What does the tolowercase() method of class String do? Used by permission. Page 36 of 38

It creates a new String which is a lower case version of the original string. Cascaded String Operations Sometimes a method of a String creates another String, and then a method of that second String is invoked to create a third String (and so on). This is sometimes called a cascade. Usually a cascade involves intermediate temporary objects. Look at these lines of code: Hint: decide what the parameter is by carrying out the operations of " MY LOVE".trim().toLowerCase(). Then decide what string invokes the startswith() method. QUESTION 26: What does the above write to the monitor? Used by permission. Page 37 of 38

Both start with the same letters. " MY LOVE".trim().toLowerCase() creates the temporary string "my love". "burns.tolower() creates the temporary string "my love is like a red, red rose." The parameter string starts with the same characters as the tolower()method's string. End of the Chapter That was a complicated question. I hope you rose to the occasion. If you got burned, review the example. You may wish to review the following. An easy way to construct a String. The null value. How an object becomes garbage. String class description. String concatenation. Shorthand notation for String concatenation. Strings as immutable objects. Overloaded operators. Length of a string. charat() method Substrings The trim() method. The startswith() method. Cascaded operations Used by permission. Page 38 of 38