I am trying something like
String s = "test string";
for(Character c: s) {
}
The compiler reports error. I am wondering the reason why I could not use foreach with String?
I am trying something like
String s = "test string";
for(Character c: s) {
}
The compiler reports error. I am wondering the reason why I could not use foreach with String?
 
    
    The reason is set out in JLS 14.14.2:
EnhancedForStatement: for ( {VariableModifier} LocalVariableType VariableDeclaratorId : Expression ) Statement...
The type of the
Expressionmust be a subtype of the raw typeIterableor an array type (§10.1), or a compile-time error occurs.
A String is not a subtype of Iterable or an array type.  Therefore .... compilation error.
As @shmosel mentions, you can iterate over the char[] returned by s.toCharArray().  However, that will create a new array1.
1 - ... unless your JVMs JIT compiler is smart enough to optimize that away. I don't think they currently can do that, and I wouldn't bet on the Java designers wanting to implement that optimization.
 
    
    