For loop structure for arrays

  • In order to access an array, like any other object, we need its reference.
  • In your case, cats is the field variable that holds the array reference.
  • The iterable variable k holds a copy of an item of the cats[] array each iteration.
  • Mutating k’s copy doesn’t change the original value inside the cats[] array.
  • So if we need to mutate the contents of cats[], we need a vanilla for ( ; ; ) style loop.
  • Use the for ( : ) style when you just need to read the contents rather than change them.
4 Likes