"Changing" a String

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

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 "make a change" to a string, but to then attempt to change an immutable object. When you think "make a change" 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. println() is called with the new reference, so the new string is written.

changing a reference variable

QUESTION 3:

Which character corresponds to index 0 in the following string?

I recognize the vestiges of an old flame.