More about Strings

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

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.