An iterator in Java specifically applies to a collection of discrete items (objects). A String is not really a "collection" of discrete characters. It is a single entity that happens to consist of characters. Therefore, it does not make sense (in some cases, or most) in the context of Collections (which is what iterators are for) to treat each individual character as a discrete entity. It makes sense (in some cases or most) to treat the String as a whole. That being said, you can treat a String as a collection or characters and access each character like this:
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
Or as others have said:
for(char c : str.toCharArray()) {
System.out.println(c);
}
Also note that you cannot modify a character of a String in place because Strings are immutable. The mutable companion to a String is StringBuilder (or the older StringBuffer).
EDIT
To clarify based on the comments on this answer. I'm trying to explain why there is no Iterator on a String
. I'm not trying to say that it's not possible. The question is if it makes sense to have an iterator on just a String
. String
provides CharSequence
, which, if conceptually, is different from a String
. A String
is usually thought of as a single entity, whereas CharSequence
is exactly that: a sequence of characters. It would make sense to have an iterator on a sequence of characters (i.e., on CharSequence
), but not simply on a String
itself.
As Foxfire has rightly pointed out in the comments, String
implements the CharSequence
interface, so type-wise, a String
is a CharSequence
. Semantically, it seems to me that they are two separate things - I'm probably being pedantic here, but when I think of a String
I usually think of it as a single entity that happens to consist of characters. Consider the difference between the sequence of digits 1, 2, 3, 4
and the number 1234
. Now consider the difference between the string abcd
and the sequence of characters a, b, c, d
. I'm trying to point out this difference.
In my opinion, asking why String
doesn't have an iterator is like asking why Integer
doesn't have an iterator so that you can iterate over the individual digits.
I might be splitting hairs, but I was only trying to help ;).