# For-Each Loops

For-Each loops are different from the other loops mentioned in [Loops](/intro-to-frc-programming-romi/intro-to-java/fundamentals-of-java/loops.md), as they are specifically designed for traversing an array (accessing every element).&#x20;

Let's say this was an array that you wanted to traverse through.

```java
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
```

If you wanted to add one to each value, for instance, your code needs to know several properties of the array. If you wanted to execute this with a for-loop, you'd need to know the start and length, just to name a few.&#x20;

This will become very bothersome. To tackle this problem, the creators of Java implemented a simple solution for you.&#x20;

```java
for (int num : arr) {
   System.out.println(num + ", "); /* output: 1, 2, 3, 4, 5, 6, 7, 8, */
}
```

Here's the syntax:

```java
for (Object item : Object[] collection) {
    [code]
}
```

You might be wondering why I'm putting "Object" here as the type. This is because as long as the collection stores two items in an array of some sort, this loop can work on it.&#x20;

### Item

This is the current item that the for-each loop is on. However, you can only access its value— you can't change it or anything.

### Collection

This is just the collection that the for-each loop is traversing through. The collection can be basically anything that can hold more than one value.

{% hint style="info" %}
If you are using a for-each loop on a collection, do NOT modify it as you're traversing through the collection or you'll have a fun time dealing with logic errors.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://velocity-raptors-9450.gitbook.io/intro-to-frc-programming-romi/intro-to-java/advanced-concepts/for-each-loops.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
