One New Object per Character

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
public static String reverse( String data )
{
String rev = new String();
for ( int j=data.length()-1; j >= 0; j-- )
rev += data.charAt(j);
return rev;
}

How many objects does reverse() construct in this example?

Answer:

The length of the input String, plus one.

One New Object per Character

With the input "Hello" six Strings are constructed (including the first, empty String) because each time the following statement executes, a new String is created:

rev += data.charAt(j);

As the statement starts to execute, rev refers to a String. The concatenation operator + creates a new String, a copy of the old one but with one more character on the end. The new String reference is assigned to rev. The old String is now garbage.

This is fine for programs that do a moderate amount of character manipulation. But such abundant construction of objects will slow down a program that does a great deal of character manipulation. Examples of such programs include word processors, compilers, assemblers, data base management systems, and many others.

QUESTION 5:

Could an array of char be used to speed up this program?