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?

A good answer might be:

The length of the input string, plus one.

One New Object per Character

When the input is "This is argument 0" 19 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 with part of the final result in it. A new string is created with one more character on the end. The new string reference is assigned to rev (the old string is now garbage).

While fine for programs that do moderate character manipulation, such abundant construction of objects will slow down a program that does a great deal of character manipulation. Such programs are word processors, compilers, assemblers, data base programs, and many others. You will soon see a way to greatly speed up the example program.

QUESTION 4:

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