String Objects are Immutable

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
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.

String Objects are Immutable

String objects are immutable which means that once a String has been constructed, it never can be changed. This has many advantages in making programs understandable and reliable. For example, if a method has a reference to a String, that String will always contain the same characters, 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 does the main() method of this program print out?