Skip to main content
Engineering LibreTexts

16.10: The Enhanced for Loop

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)

    Since traversing arrays is so common, Java provides an alternative syntax that makes the code more compact. For example, consider a for loop that displays the elements of an array on separate lines:

    for (int i = 0; i < values.length; i++) {
        int value = values[i];

    We could rewrite the loop like this:

    for (int value : values) {

    This statement is called an enhanced for loop. You can read it as, “for each value in values”. It’s conventional to use plural nouns for array variables and singular nouns for element variables.

    Notice how the single line for (int value : values) replaces the first two lines of the standard for loop. It hides the details of iterating each index of the array, and instead, focuses on the values themselves.

    Using the enhanced for loop, and removing the temporary variable, we can write the histogram code from the previous section more concisely:

    int[] counts = new int[100];
    for (int score : scores) {

    Enhanced for loops often make the code more readable, especially for accumulating values. But they are not helpful when you need to refer to the index, as in search operations.

    for (double d : array) {
        if (d == target) {
            // array contains d, but we don't know the index

    16.10: The Enhanced for Loop is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey.

    • Was this article helpful?