This demonstration assumes familiarity with basic String methods. See Working with String objects for details.

Also see while and for loops.

Visit each character in a String

String str = "Brandon Horn";
//            012345678901

System.out.println(str.length());  // prints 12

for(int index = 0; index < str.length(); index++)
{
    System.out.println(str.substring(index, index + 1));
}

The loop prints each character from str on its own line.

A for loop is appropriate since the starting and ending indexes are known. The loop accesses a single character from str (the character at index) each time it is run.

Building a new String

String str = "Brandon Horn";
//            012345678901

String rStr = "";

for(int index = str.length() - 1; index >= 0; index--)
{
    rStr += str.substring(index, index + 1);
}

System.out.println(rStr);  // prints nroH nodnarB

The code builds a new String that contains the characters from str in reverse order.

rStr is initialized to the empty String. The empty String is different from null and from an uninitialized variable. Initializing rStr to the empty String allows values to be concatenated with it to form new String objects.

index is initialized to str.length() - 1 since that is the last valid index in str. Initializing index to str.length() is a common mistake. In a basic loop through str, the loop condition is often index < str.length(), which excludes str.length().

Comments

Comment on Looping through a String