Revised Reverse

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

Answer:

Yes.

Revised Reverse

The reverse() method reverses the order of the characters in a StringBuffer object. Unlike the methods of immutable objects, this method changes the data of its object. For practice, let us write another method that does this.

The append() method puts a new character at the end of a StringBuffer object. No new object is created. We can use this method to build up the reversed characters as the original String is scanned from right to left:

public class ReverseTester
{

  public static String reverse( String data )
  {
    StringBuffer temp = new StringBuffer();

    for ( int j=data.length()-1; j >= 0; j-- )  // scan the String from right to left
      temp.append( data.charAt(j) );            // append characters on the right

    return temp.toString();      // return a String created from the StringBuffer
  }

  public static void main ( String[] args )
  {
    System.out.println( reverse( "Hello" ) );
  }
}

In this version of reverse(), only two new objects are created: the StringBuffer and the String object that is returned to the caller.

QUESTION 8:

Does this program make any assumptions about the size of the original String?