0

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?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

1 Answers1

4

The reason is set out in JLS 14.14.2:

EnhancedForStatement:
    for ( {VariableModifier} LocalVariableType VariableDeclaratorId : Expression ) Statement 

...

The type of the Expression must be a subtype of the raw type Iterable or 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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216