String Reverser

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:

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

String Reverser

With paper and pencil, reversing a string is easy. Copy characters from the original string right to left to the new string 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.

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

The body of the for loop executes once per character.

QUESTION 4:

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