Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.5 Iteration — traversing a string

Lesson

Looking at each character

A String is a sequence of characters at positions 0, 1, 2, .... s.length() gives how many there are, and s.charAt(i) gives the character at position i. To visit them all, loop i from 0 up to but not including s.length().


Worked example

String s = "cat";
for (int i = 0; i < s.length(); i++) {
    System.out.println(s.charAt(i));
}

Positions 0, 1, 2 hold c, a, t. Output is c, a, t on three lines.


▶ Try it: run this, then change "cat" to your own word and re-run. Then try changing < to <= — you will get an out-of-bounds error, because there is no character at position length().



What is s.length() when s is "hello"?


For s = "cat", match each call to its result.


Why does the loop condition use i < s.length() and not i <= s.length()?


True or false?


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    String s = "hi";
    for (int i = 0; i < s.length(); i++) {
        System.out.println(s.charAt(i));
    }
}}