Topic 1 - Variables and Data Types
Topic 2 - Conditionals and Strings
Topic 3 - Loops
Topic 4 - Arrays
Topic 5 - File Handling
Semester 1 Projects
Topic 6 - Classes/Objects and Methods
Topic 7 - ArrayLists
Semester Projects

For Loops and Strings

Loops are often used for String Traversals or String Processing where the code steps through a string character by character. In our previous unit, we learned to use String objects and built-in string methods to process strings. In this lesson, we will write our own loops to process strings.

Remember that strings are a sequence of characters where each character is at a position or index starting at 0. You can image a string like this:

The first character in a Java String is at index 0 and the last character is at length() – 1. So loops processing Strings should start at 0!

A but how can we use loops to do interesting things with strings? For loops help us visit every character in a string and do something with that character. Since a for loop gives us a number that increases, or decreases, with each iteration, we can use it to access different parts of the string.

In the following code the loop counter increases by one, and each time it prints a letter from the string in a different line, with System.out .println():

With a while-loop:

With a for-loop:

.charAt()

So what’s happening in the code above? We use the string method .chartAt() to get a character at an index. If we have a string

String name = "Unit"; 

and we follow it with

char letter = name.charAt(2);

then the letter variable will be assigned the value “i”, which is the third letter in the string.

IndexOutOfBoundException

One of the most common errors you will come across is “Index out of bounds exception”.

Let’s look at the following string again and call is testString:

This string has 14 characters, starting at index 0 and ending at index 13.

if we do this

char letter = testString.charAt(5)

the code will work as expected. But what happens if we try to do this:

char letter = testString.charAt(14)

or this

char letter = testString.charAt(1000)

well, that string ends at index 13 so we are going Out Of Bounds with the Index hence IndexOutOfBoundsException is returned by the compiler.

The error message will look like this:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 26
 at java.lang.String.charAt(String.java:658)
 at Main.main(Main.java:8)
exit status 1

The error is saying that on line 8 or Main.java an error occurred where you when out of range and tried to access something at index 19.

One of the most common things to happen with a loop is that your loop variable will increase to a number that is out of bounds of the indexes available for a string. Let’s try to fix this error below:

Practice problem