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().
String
0, 1, 2, ...
s.length()
s.charAt(i)
i
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.
c
a
t
▶ 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().
"cat"
<
<=
length()
What is s.length() when s is "hello"?
s
"hello"
For s = "cat", match each call to its result.
s = "cat"
Why does the loop condition use i < s.length() and not i <= s.length()?
i < s.length()
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)); } }}