String str = new String("I recognize the vestiges of an old flame."); str.substring( 16 ); System.out.println( str );
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 above phrase.)
Programmers often forget that
String objects are immutable.
String object has been constructed, it cannot be
This line of code:
str.substring( 16 );
correctly 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 points to the original object
and does not change, 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?