More about Strings

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: More about Strings
Printed by: Guest user
Date: Sunday, July 7, 2024, 6:08 AM

Description

This chapter accompanies the previous one. Read it for even more info on Strings.

1. More about Strings

String objects are frequently used in programs. This chapter provides extra practice in using them.

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 AP-CS 2008 examination.

Chapter Topics:

      • Strings are Immutable
      • Indexing Strings
      • substring()
      • indexOf()

Question 1:

What does the following code write?

public 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: Bradley Kjell, http://programmedlessons.org/Java9/chap45/ch45_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Strings are Immutable!


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?

3. "Changing" a String


Answer:

public 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:

  1. Compute a new String object.
  2. 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.

changingAstring (1)


Question 3:

Which character corresponds to index 0 in the following string?

    I recognize the vestiges of an old flame.

4. String Indexing


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.

stringIndexing

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.

Code
Value
"buttons".length()
"buttons and bows".length()
"buttons\tand\tbows".length()
"".length()


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() )

5. Versions of substring()


Answer:

The program will throw a NullPointerException (and usually stop running).

Notice that there is no object because the reference variable contains null. Since there is no
object, there is no length() to run.

Versions of substring()

There are two versions of substring:

substring( int from ) 
Create a new object that contains the characters of the method's string from index from to the end of the string.
Throws an IndexOutOfBoundsException if from is negative or larger than the length of the string.
substring( int from, int to )
Create a new object that contains the characters of the method's string from index from to index to-1.
Throws an IndexOutOfBoundsException if from is negative or if from is larger than to.

There are some tricky rules about the first version of the method:

  1. 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).
  2. 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?

Line of code:
New String
String line = "buttercup" ;
String a = line.substring( 6 );
String b = line.substring( 0 );
String c = line.substring( 9 );
String d = line.substring( line.length() );
String e = line.substring( line.length()+1 );
String f = line.substring( -1 );

6. Play with substring()


Answer:

(a new String is created,
containing all the characters of the original)
Line of code:
New String
String line = "buttercup" ;
buttercup
String a = line.substring( 0 );
buttercup
String b = line.substring( 6 );
cup
String c = line.substring( 9 );
(an empty string is created)
String d = line.substring( line.length() );
(an empty string is created)
String e = line.substring( line.length()+1 );
EXCEPTION
String f = line.substring( -1 );
EXCEPTION

Play with substring()

Play with substring() with the following demonstration. The parameter for substring() must be an integer literal like 0 or 12.

Try some other strings than the one suggested. Be sure to enclose the characters of the string with quote marks. (However, the demonstration does not support escape characters in the string, so don't try tab characters.)

The resulting string may sometimes be the empty string or contain spaces. The quote marks in the result are not part of the string that the substring method produces.

In the original version of this page the demonstration was a Java applet. The demonstration uses Javascript, but works the same as Java.

If the demonstration does not work on your computer, Javascript might not be enabled. Just skip this page.

String line =  ; // Enter a string here between quotes

String result = line.substring(  ) ; // Enter a single integer parameter

result: 


Question 6:

The empty string "" is a legitimate String object and it has the substring( int from ) method.

What are the valid values for its from parameter?

(Test your answer with the above demonstration.)

7. Two-parameter substring()


Answer:

Only one value is legitimate: 0 .

Two-parameter substring()

substring( int from, int to )
Create a new object that contains the characters of the method's string from index from to index to-1.
Throws an IndexOutOfBoundsException if from is negative or if from is larger than to.


There is a second version of substring(). Remember those tricky rules about the second version of the method:

  1. If from is negative, an IndexOutOfBoundsException is thrown.
  2. If from is larger than to, an IndexOutOfBoundsException is thrown.
  3. If to is larger than the length, an IndexOutOfBoundsException is thrown.
  4. 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?

Line of code:
New String
String line = "buttercup" ;
String a = line.substring( 0, 6 );
String b = line.substring( 6, 9 );
String c = line.substring( 0, 1 );
String d = line.substring( 0, 0 );
String e = line.substring( 5, 5 );
String f = line.substring( 4, line.length()+1 );
String g = line.substring( 6, 3 );

8. More Play with substring()


Answer:

Line of code:
New String
String line = "buttercup" ;
"buttercup"
String a = line.substring( 0, 6 );
"butter"
String b = line.substring( 6, 9 );
"cup"
String c = line.substring( 0, 1 );
"b"
String d = line.substring( 0, 0 );
""
String e = line.substring( 5, 5 );
""
String f = line.substring( 4, line.length()+1 );
EXCEPTION
String g = line.substring( 6, 3 );
EXCEPTION

More Play with substring()

Play with substring() with the following demonstration. The parameters for substring() must be integer literals like 0 or 12.

Try some other strings than the one suggested. Be sure to enclose the characters of the string with quote marks. (However, the demonstration does not support escape characters in the string, so don't try tab characters.)

The resulting string may sometimes be the empty string or contain spaces. The quote marks in the result are not part of the string that the substring method produces.

If the demonstration does not work on your computer, Javascript might not be enabled. Just skip this page.

String line =  ; // Enter a string here between quotes

String result = line.substring(  , ) ; // Enter integer parameters from and to

result: 


Question 8:

Is the following correct? What string does it create?

    String str = "buttercup" ; str = str.substring(3).substring(1,4);

9. The indexOf() Methods


Answer:

erc

The second statement works like this:

buttercup

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:

indexOf( String str )
Returns the index of the first occurrence of str or -1 if str is not found.


For example, the following puts the value 4 into location.

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

The following puts the value -1 into location.

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


Question 9:

What does the following put into location?

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

10. Play with indexOf()


Answer:

6

The first occurrence 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().

Try searching for the second occurrence of "ant" in the line. Pay attention to spaces.


String line =  ; // Enter a string here between quotes

String target =  ; // Enter a string here between quotes

int location = line.indexOf( target );

location: 


Question 10:

What is the index of the empty string "" ?

11. Tail of a Substring


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:

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

String statement = "value = alpha*beta + gamma;"  ;

int loc = statement.indexOf( "=" );
if ( loc !=  )
{
  String left = statement.substring(  0,  );
  String right = statement.substring(  + 1 );
}

Question 11:

Ooops. The fragment is not completed. Fill in the blanks.

12. Second Occurrence


Answer:

    String statement = "value = alpha*beta + gamma;"  ;
    
    int loc = statement.indexOf( "=");
    if ( loc != -1 )
    {
      String left = statement.substring(  0, loc );
      String right = statement.substring( loc + 1  );
    }

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?

13. End of the Chapter


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.