A New 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

Answer:

a good walk spoiled.

A New String

Here is a picture of what happens as the program runs. When the program first starts there are two reference variables, but no objects. When the first statement executes,

    String str = new String( "Golf is a good walk spoiled." ); // create the original object

it creates a String object and puts a reference to that object in the variable str. (The picture shows only the data part of the objects.)

picture showing object creation

When the second statement executes,

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

a new object is created that contains a substring of the characters in the first object. The variable sub is assigned a reference to this object.

QUESTION 12:

Does running the substring() method of a String change that String?