Menu
Coddy logo textTech

Using For Loop

Part of the Fundamentals section of Coddy's Java journey — lesson 64 of 73.

Iteration means going through elements one by one in a sequence. With arrays, we can access each element systematically using different methods.

The most common way to iterate through an array is using a for loop:

String[] fruits = {"apple", "banana", "orange"};
	for (int i = 0; i < fruits.length; i++) {    
	System.out.println(fruits[i]);
}

Output:

apple
banana
orange
challenge icon

Challenge

Easy

Create a program that starts with an array of words, and prints a new array containing only the words longer than 5 characters

Reminder: to print an array use the toString() function: System.out.println(Arrays.toString(arr));

Check the hint if you are stuck.

Cheat sheet

To iterate through an array, use a for loop with an index variable:

String[] fruits = {"apple", "banana", "orange"};
for (int i = 0; i < fruits.length; i++) {    
    System.out.println(fruits[i]);
}

To print an array, use Arrays.toString():

System.out.println(Arrays.toString(arr));

Try it yourself

import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        String[] arr = text.split(",");
        // Write your code below
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals