13
Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 1 of 13 “Chapter 29B: More about Strings” Bradley Kjell (Revised 06/12/2008) String objects are frequently used in programs. This chapter provides extra practice in using them. Chapter Topics: Strings are Immutable Indexing Strings substring() indexOf() Note: the String class is one of the classes that Advanced Placement Computer Science students are expected to know well. This chapter was written after the author observed an unfortunate number of mistakes involving Strings in the APCS 2008 examination. QUESTION 1: What does the following code write? class ImmDemo { public static void main ( String[] args ) { String str = new String("I recognize the vestiges of an old flame."); str.substring( 16 ); System.out.println( str ); } }

“Chapter 29B: More about Strings” Bradley Kjell (Revised … · 2018. 11. 27. · “Chapter 29B: More about Strings” Bradley Kjell (Revised 06/12/2008) String objects are frequently

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 1 of 13

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

    String objects are frequently used in programs. This chapter provides extra practice in using them. Chapter Topics: ▪ Strings are Immutable ▪ Indexing Strings ▪ substring() ▪ indexOf() Note: the String class is one of the classes that Advanced Placement Computer Science students are expected to know well. This chapter was written after the author observed an unfortunate number of mistakes involving Strings in the APCS 2008 examination. QUESTION 1: What does the following code write? class ImmDemo { public static void main ( String[] args ) { String str = new String("I recognize the vestiges of an old flame."); str.substring( 16 ); System.out.println( str ); } }

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 2 of 13

    Answer: The program writes out: I recognize the vestiges of an old flame. The code is syntactically correct and will compile and run, but what it does might not be what the author intended. (The author probably intended to write out a substring of the phrase.) Strings are Immutable! Programmers often forget that String objects are immutable. Once a String object has been constructed, it cannot be changed. This line of code:

    str.substring( 16 );

    creates a new object, containing a substring of the characters of the original object. However, the original object is not changed. Since the reference variable str continues to point to the original object, the new object immediately becomes garbage. The next statement

    System.out.println( str );

    writes out the characters in the original object. QUESTION 2: How would you modify the program so that the new substring is written?

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 3 of 13

    Answer: class ImmDemo { public static void main ( String[] args ) { String str = new String("I recognize the vestiges of an old flame."); str = str.substring( 16 ); System.out.println( str ); } }

    "Changing" a String A common mistake is to think "change a string", but to then attempt to change an immutable object. When you think "change a string" you need to do two things: ▪ Compute a new String object. ▪ Assign the reference to the new String to a reference variable. The diagram shows how the second version of the program works. The reference variable str is first assigned a reference to the original object. Then a new object is constructed by substring(). The new reference is assigned to str. Then the println() method is called with the new reference, so the new string is written.

    QUESTION 3: Which character corresponds to index 0 in the following string? I recognize the vestiges of an old flame.

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 4 of 13

    Answer: Character 'I' (the beginning character of the string). String Indexing The beginning character of a string corresponds to index 0 and the last character corresponds to the index (length of string)-1.

    The length of a string is the number of characters it contains, including spaces, punctuation, and control characters. Fill in the following table by clicking on the buttons.

    The sequence "\t" stands for a single character, a tab character. Each tab character counts as one character (although it might be displayed on a monitor or printer using several spaces). Be careful about the difference between an empty string, and a null reference. An empty string is an object that contains no characters, and so has length 0. A null reference means there is no object present. QUESTION 4: What does the following code write? String myString = null; System.out.println("The length is: " + myString.length() )

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 5 of 13

    Answer: The program will throw a NullPointerException (and usually stop running). Versions of substring() There are two versions of substring:

    There are some tricky rules about the first version of the method: ▪ If from 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 from is greater than the length of the original string, or a negative value, a

    IndexOutOfBoundsException is thrown (and for now, your program crashes).

    QUESTION 5: What do the following statements create?

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 6 of 13

    Answer:

    Play with substring() Play with substring() using the following applet. The parameter for substring() (in this applet) must be an integer literal like 0 or 12. http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_6.html Try some other strings than the one suggested. Be sure to enclose the characters of the string with quote marks. (However, the applet does not support escape characters in the string, so don't try tab characters.) QUESTION 6: The empty string "" is a legitimate String object and thus has the substring( int from ) method. What are the valid values for its from parameter? (Test your answer with the above applet.)

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 7 of 13

    Answer: Only one value is legitimate: 0 . Two-parameter substring() There is a second version of substring():

    Remember those tricky rules about the second version of the method: ▪ If from is negative, an IndexOutOfBoundsException is thrown. ▪ If from is larger than to, an IndexOutOfBoundsException is thrown. ▪ If to is larger than the length, an IndexOutOfBoundsException is thrown. ▪ If from equals to, and both are within range, then an empty string is returned. These rules make sense. If something can't be done, Java throws an exception. QUESTION 7: What do the following statements create?

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 8 of 13

    Answer:

    More Play with substring() Play with substring() using the following applet. The parameter for substring() (in this applet) must be an integer literal like 0 or 12. http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_8.html Try some strings other than the one suggested. Be sure to enclose the characters of the string with quote marks. (However, the applet does not support escape characters in the string.) QUESTION 8: Is the following correct? What string does it create? String str = "buttercup" ; str = str.substring(3).substring(1,4);

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 9 of 13

    Answer: erc

    The second statement works like this:

    The final string could just as easily have been created with a single call: str = str.substring(4,7);

    The indexOf() Methods There are four varieties of indexOf() in the Java library. Only the following may be included on the AP examination:

    For example

    String example = "The sea is calm to-night." ; int location = example.indexOf( "sea" );

    puts the value 4 into location. This String example = "The sea is calm to-night." ; int location = example.indexOf( "rats" );

    puts the value -1 into location. QUESTION 9: What does the following put into location?

    String example = "The sea is calm to-night." ; int location = example.indexOf( "a" );

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 10 of 13

    Answer: 6 The first occurance of the string "a" within the method's string is at index 6. Play with indexOf() Play with the following to gain insight into indexOf(). http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_10.html Try searching for the second occurence of "ant" in the line. (Hint: pay attention to spaces.) QUESTION 10: What is the index of the empty string "" ?

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 11 of 13

    Answer: 0 Tail of a Substring Here is a fragment that computes the tail of the example string, starting with the first "a":

    String example = "The sea is calm to-night." ; String tail = example.substring( example.indexOf( "a" ) );

    The way this works is:

    indexOf() and substring() can be used to chop a string into useful pieces. Here is a fragment that chops an assignment statment into the part to the left of the assignment operator and the part to the right:

    QUESTION 11: Ooops. The fragment is not completed. Fill in the blanks.

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 12 of 13

    Answer:

    Second Occurrence A correct line of a Java program only rarely includes two assignment operators. Here is a program fragment that inspects a line for this: String line = "alpha = beta + 23 = 99;" ; int spot = line.indexOf( "=" ); if ( spot != -1 ) { String newLine = line.substring( spot+1 ) ; if ( newLine.indexOf("=") > 0 ) { System.out.println( "Possible Bad Line: " + line ); } }

    The statement String newLine = line.substring( spot+1 ) ;

    computes the tail of the original line, starting with the character after the first = sign. The clause newLine.indexOf("=") > 0 detects = anywhere but at the beginning of this new line (where it would be OK because it would be part of "=="). QUESTION 12: What if you did not have the startsWith(String str) method? Could you use other methods to replace it?

  • Source URL: http://chortle.ccsu.edu/java5/Notes/chap29B/ch29B_1.html Saylor URL: http://www.saylor.org/courses/cs101/#3.4 © Bradley Kjell Saylor.org Used by permission. Page 13 of 13

    Answer: line.startsWith(str)

    could be replaced by (line.indexOf(str)==0)

    End of the Chapter You have reached the tail end of the chapter. Click on a subject that interests you to go to where it was discussed.

    • Immutable strings • String Indexing • substring() • indexOf()