Many Java framework classes implement Iterable, however String does not. It makes sense to iterate over characters in a String, just as one can iterate over items in a regular array.
Is there a reason why String does not implement Iterable?
There really isn’t a good answer. An iterator in Java specifically applies to a collection of discrete items (objects). You would think that a
String, which implementsCharSequence, should be a “collection” of discrete characters. Instead, it is treated as a single entity that happens to consist of characters.In Java, it seems that iterators are only really applied to collections and not to a string. There is no reason why it is this way (near as I can tell – you would probably have to talk to Gosling or the API writers); it appears to be convention or a design decision. Indeed, there is nothing preventing
CharSequencefrom implementingIterable.That said, you can iterate over the characters in a string like so:
Or:
Or:
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 a possible rationale as to why there is no Iterator on a
String. I’m not trying to say that it’s not possible; indeed I think it would make sense forCharSequenceto implementIterable.StringprovidesCharSequence, which, if only conceptually, is different from aString. AStringis usually thought of as a single entity, whereasCharSequenceis exactly that: a sequence of characters. It would make sense to have an iterator on a sequence of characters (i.e., onCharSequence), but not simply on aStringitself.As Foxfire has rightly pointed out in the comments,
Stringimplements theCharSequenceinterface, so type-wise, aStringis aCharSequence. Semantically, it seems to me that they are two separate things – I’m probably being pedantic here, but when I think of aStringI usually think of it as a single entity that happens to consist of characters. Consider the difference between the sequence of digits1, 2, 3, 4and the number1234. Now consider the difference between the stringabcdand the sequence of charactersa, b, c, d. I’m trying to point out this difference.In my opinion, asking why
Stringdoesn’t have an iterator is like asking whyIntegerdoesn’t have an iterator so that you can iterate over the individual digits.