String str = new String("I recognize the vestiges of an old flame."); str.substring( 16 ); System.out.println( str );
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.)
Programmers often forget that
String objects are immutable.
String object has been constructed, it cannot be
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.
How would you modify the program so that the new substring is written?