go to previous page   go to home page   go to next page
String data = new String("Turtle");
data = data + 's' ;

Answer:

Yes. The last statement constructs a new String, that contains the characters "Turtles", and places a reference to the new String in the reference variable data. The previous String is now garbage, and will be recycled by the garbage collector.

This is an awful lot of work for just one character.


String Objects are Immutable

String objects are immutable. Once a String has been constructed, it never can be changed. This has many advantages in making programs understandable and reliable.

If a method has a String, that String will reliably always be the same, no matter what other methods are called and what they do. For this reason, a program that does only a moderate amount of character manipulation should do it all using class String.

Examine the following program:


public class Immutable
{

  public static void mysteryMethod( String data )
  {
    . . . .
  }

  public static void main ( String[] args )
  {
    String str = "An Immutable String" ;
    mysteryMethod( str );
    System.out.println( str );
  }
}

QUESTION 2:

What is printed by main() ?