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 );
}
}
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:
String
object.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.
Which character corresponds to index 0 in the following string?
I recognize the vestiges of an old flame.