go to previous page   go to home page   go to next page

Answer:

You could reverse a string by copying characters from one string starting at the end to another, starting at the beginning.


String Reverser

Reversing a String

With paper and pencil, reversing a string is easy. Copy characters from the original string going right to left to the new string going left to right.

The reverse() method in the following program follows that idea. The variable j indexes characters in the original string starting at the rightmost character, data.length()-1, and moves left until it reaches the first character. Each character is appended on the right of a new String.

The body of the for loop executes once per character.

The method constructs a new String leaving the parameter untouched. It returns a reference to that new String.


public class ReverseTester
{

  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;
  }

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

QUESTION 4:

(Tricky Thought Question: ) How many objects does reverse() construct in this example?


go to previous page   go to home page   go to next page