-1

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
  • 23,314
  • 47
  • 144
  • 221

1 Answers1

3

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.

Community
  • 1
  • 1
Stephen C
  • 669,072
  • 92
  • 771
  • 1,162