Home › Learn › Java › Arrays and lists

The for-each loop

Lesson 17 of 40. Visit every element without an index.

When you want every element and do not need its position, for (String word : words) { ... } gives each element in turn; read the colon as "in". It works on arrays and on every collection, cannot run off the end, and reads as what it does. Use the indexed for when you need i, or need to change elements in place.

Joining words with a separator is a common loop with one wrinkle: the separator goes between elements, not after each, so add it before every element except the first (if (!result.isEmpty()) or a boolean flag).

int longest = 0;
for (String w : words) {
    if (w.length() > longest) {
        longest = w.length();
    }
}

Your task

Write static int countLong(String[] words, int min) returning how many words have more than min characters, static String join(String[] words, String sep) returning the words joined by the separator ("" for no words), and static boolean contains(int[] xs, int wanted) returning whether the value is in the array.

Hint 1

for (String w : words) if (w.length() > min) count++;

Hint 2

join: for (String w : words) { if (!result.isEmpty()) result += sep; result += w; } contains: return true inside the loop when found, false after it.

Show the solution
public class Main {
    static int countLong(String[] words, int min) {
        int count = 0;
        for (String w : words) {
            if (w.length() > min) {
                count++;
            }
        }
        return count;
    }

    static String join(String[] words, String sep) {
        String result = "";
        for (String w : words) {
            if (!result.isEmpty()) {
                result += sep;
            }
            result += w;
        }
        return result;
    }

    static boolean contains(int[] xs, int wanted) {
        for (int x : xs) {
            if (x == wanted) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String[] words = {"tea", "coffee", "water"};
        System.out.println(countLong(words, 3) + " " + join(words, ", "));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.