A Method that Creates a String

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   hear noise   go to next page
String stringG = new String("You know my methods, Watson.");

Answer:

Yes.

A Method that Creates a String

Many of the methods of String objects create other String objects.

For example, the substring(int begin) method creates a new String that contains a copy of part of the data in the original string. Here is a program that uses this method:

class StringDemo3
{
  public static void main ( String[] args )
  {
    String str = new String( "Golf is a good walk spoiled." ); // create the original object

    String sub = str.substring(8); //create a new object from the original

    System.out.println( sub );

  }
}

The expression

str.substring(8)

creates a new String object. That object contains its own data, which are characters copied from the original string. The original string is not changed. The copy starts with character number 8 of the original string and continues to the end. Character numbering starts at zero, so character number 8 in the original string is the first 'a'.

The substring of the original string is contained in a new String object. A reference to that new string is assigned to the reference variable sub.

QUESTION 11:

What characters are contained in the new object?